Which wpf control is best suited for this menu sce

2019-08-30 16:37发布

问题:

I need a button-style menu, i.e. horizontally arranged group of always visible buttons.
Like radiobuttons they should have a selected property, i.e. the click-command should fire only when the selected status changes to true, not on every click as with a normal button.

回答1:

Dude, this is WPF, you can use any control that fits some or any of your requirements and then simply provide a new ControlTemplate for it. Incidentally, there is no Selected or IsSelected property on a RadioButton... perhaps you were referring to the IsChecked property? This property is inherited from the ToggleButton, so that may be more appropriate.

As the ToggleButton is already a Button, you could even get away without providing a new ControlTemplate for it.

As for your requirement regarding the Click event, I don't think that you will find that functionality on any of the WPF controls, but it could be manually implemented:

private void Button_Click(object sender, RoutedEventArgs e)
{
    if (ToggleButton.IsChecked == true) 
    {
        // Do something here when the `Button.IsChecked` == true
    }
}


回答2:

RadioButton also like other Buttons fire Click event on every click. Also there is no Selected property on the RadioButton.

But if you want your MenuItems to be like Button, then you can use ToggleButton here. ToggleButton has IsChecked Property which tracks the checked state of button and Checked event which is fired when ToggleButton is Checked.

Also, if you want to automatically check/uncheck your ToggleButtons on click of other ToggleButton then you can use RadioButton as DataTemplate of your MenuItem and override its Template like below:

      <RadioButton Content="MyRadio" Click="RadioButton_Click">
            <RadioButton.Template>
                <ControlTemplate TargetType="RadioButton">
                    <ToggleButton Checked="ToggleButton_Checked" IsChecked="{Binding IsChecked, RelativeSource={RelativeSource TemplatedParent}}" Content="{TemplateBinding Content}"/>
                </ControlTemplate>
            </RadioButton.Template>
        </RadioButton>


回答3:

It turned out that a ListBox with a horizontal layout in a WrapPanel suits my scenario perfectly. I posted the solution in another question.