Toolstrip с группой кнопок проверки - PullRequest
7 голосов
/ 17 июня 2011

Я хотел бы иметь панель инструментов с несколькими кнопками (WinFroms / c # /. Net4). Я бы хотел, чтобы нажатая кнопка была отмечена, а все остальные не отмечены, поэтому я хочу, чтобы только отмеченная кнопка была отмечена, а все остальные - нет.

Я знаю, что кнопка toolstrip имеет свойство selectedonlclick, но когда я нажимаю одну кнопку, другие кнопки также могут быть проверены. В старом добром VB6 было автоматическое решение этой проблемы: buttongroup на панели инструментов. Есть ли подобное в Winfoms?

Или я должен справиться с этим из кода ?! Переключить все остальные кнопки в непроверенное состояние при проверке одной кнопки? Если так, то это не будет моим любимым решением ...

Ответы [ 4 ]

11 голосов
/ 18 июня 2011

Назовите этот код в событиях toolStripButton_Click, и вы получите желаемый результат.

   foreach (ToolStripButton item in ((ToolStripButton)sender).GetCurrentParent().Items)
   {
       if (item == sender) item.Checked = true;
       if ((item != null) && (item != sender))
       {
          item.Checked = false;
       }
   }
2 голосов
/ 28 августа 2013

Полагаю, это старый вопрос, однако я тоже искал решение этой проблемы и в итоге сделал своего рода ToolStripRadioButton, расширив ToolStripButton. Насколько я вижу, поведение должно быть таким же, как и у обычной радиокнопки. Однако я добавил идентификатор группы, чтобы иметь возможность иметь несколько групп переключателей в одной и той же панели инструментов.

Можно добавить переключатель в панель инструментов, как обычная кнопка ToolStripButton:

Add RadioButton

Чтобы сделать кнопку более выделенной при проверке, я дал ей градиентный фон (от CheckedColor1 до CheckedColor2 сверху вниз):

Checked RadioButton gradient background

using System;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Windows.Forms;

public class ToolStripRadioButton : ToolStripButton
{
    private int radioButtonGroupId = 0;
    private bool updateButtonGroup = true;

    private Color checkedColor1 = Color.FromArgb(71, 113, 179);
    private Color checkedColor2 = Color.FromArgb(98, 139, 205);

    public ToolStripRadioButton()
    {
        this.CheckOnClick = true;
    }

    [Category("Behavior")]
    public int RadioButtonGroupId
    {
        get 
        { 
            return radioButtonGroupId; 
        }
        set
        {
            radioButtonGroupId = value;

            // Make sure no two radio buttons are checked at the same time
            UpdateGroup();
        }
    }

    [Category("Appearance")]
    public Color CheckedColor1
    {
        get { return checkedColor1; }
        set { checkedColor1 = value; }
    }

    [Category("Appearance")]
    public Color CheckedColor2
    {
        get { return checkedColor2; }
        set { checkedColor2 = value; }
    }

    // Set check value without updating (disabling) other radio buttons in the group
    private void SetCheckValue(bool checkValue)
    {
        updateButtonGroup = false;
        this.Checked = checkValue;
        updateButtonGroup = true;
    }

    // To make sure no two radio buttons are checked at the same time
    private void UpdateGroup()
    {
        if (this.Parent != null)
        {
            // Get number of checked radio buttons in group
            int checkedCount = this.Parent.Items.OfType<ToolStripRadioButton>().Count(x => x.RadioButtonGroupId == RadioButtonGroupId && x.Checked);

            if (checkedCount > 1)
            {
                this.Checked = false;
            }
        }
    }

    protected override void OnClick(EventArgs e)
    {
        base.OnClick(e);
        this.Checked = true;
    }

    protected override void OnCheckedChanged(EventArgs e)
    {
        if (this.Parent != null && updateButtonGroup)
        {
            foreach (ToolStripRadioButton radioButton in this.Parent.Items.OfType<ToolStripRadioButton>())
            {
                // Disable all other radio buttons with same group id
                if (radioButton != this && radioButton.RadioButtonGroupId == this.RadioButtonGroupId)
                {
                    radioButton.SetCheckValue(false);
                }
            }
        }
    }

    protected override void OnPaint(PaintEventArgs e)
    {
        if (this.Checked)
        {
            var checkedBackgroundBrush = new LinearGradientBrush(new Point(0, 0), new Point(0, this.Height), CheckedColor1, CheckedColor2);
            e.Graphics.FillRectangle(checkedBackgroundBrush, new Rectangle(new Point(0, 0), this.Size));
        }

        base.OnPaint(e);
    }
}

Возможно, полезно и для других.

1 голос
/ 14 июля 2011

Я не знаю, как это сделать в конструкторе, но это довольно просто сделать в коде:

readonly Dictionary<string, HashSet<ToolStripButton>> mButtonGroups;

...

ToolStripButton AddGroupedButton(string pText, string pGroupName) {
   var newButton = new ToolStripButton(pText) {
      CheckOnClick = true
   };

   mSomeToolStrip.Items.Add(newButton);

   HashSet<ToolStripButton> buttonGroup;
   if (!mButtonGroups.TryGetValue(pGroupName, out buttonGroup)) {
      buttonGroup = new HashSet<ToolStripButton>();
      mButtonGroups.Add(pGroupName, buttonGroup);
   }

   newButton.Click += (s, e) => {
      foreach (var button in buttonGroup)
         button.Checked = button == newButton;
   };

   return newButton;
}
0 голосов
/ 17 июня 2011

Я немного не сделал этого, но если вы используете групповую рамку вокруг переключателей, она будет позволять проверять только одну за раз.

...