开发者

ToolStripButton = "Pressed"

I got a toolstripbutton, and when I click it, I want to make it stay "pressed" or "selected". Like a switch. And when I click another, make the pressed one "unpressed" again开发者_开发知识库. Any ideas?


I think you want to use the CheckOnClick property. Set it to true, and the button should behave as you describe. In order to get (or set) the current state, use the Checked property.

Here is a full working sample:

public partial class Form1 : Form
{
    private readonly IEnumerable<ToolStripButton> mutuallyExclusiveButtons;

    public Form1()
    {
        InitializeComponent();
        mutuallyExclusiveButtons = new[] { firstButton, secondButton };
    }

    private void ToolStripButton_Click(object sender, EventArgs e)
    {
        ToolStripButton button = sender as ToolStripButton;
        if (button != null && button.Checked && 
            mutuallyExclusiveButtons.Contains(button))
        {
            foreach (ToolStripButton item in mutuallyExclusiveButtons)
            {
                if (item != button) item.Checked = !button.Checked;
            }
        }
    }
}

firstButton and secondButton are ToolStripButtons, both have CheckOnClick set to true, and their Clicked events hooked up to ToolStripButton_Click. This works also if there are more than two buttons in the group of buttons in which only one should be checked, just add any needed additional buttons to the mutuallyExclusiveButtons sequence.


As ChrisF said, what you are looking for is the "Checked" property. (The "CheckOnClick" property is actually not what you want, since you want a sort of mutually exclusive toggle between two ToolStripButtons.)

What you will need is to put code (into the click event of each button) that will set the Checked property of that button to True and the Checked property of the other button to False.

Actually, you can use CheckOnClick and then add code only to set the other button to False.


(Hmmm... I wonder when the Checked becomes set to True; can you capture the MouseUp etc. event of BOTH buttons into one handler, and uncheck BOTH buttons, and then CheckOnClick will check the appropriate one later? Just some geek stuff to complicate things unnecessarily in the name of simplifying things)


Maintain a flag as to what the status of a button is (pressed or normal). For each button press, call a method that refreshes the toolbar buttons to the correct state (either stay pressed or go back to normal).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜