Given the following code:
<MenuItem x:Name="MenuItem_Root" Header="Root">
<MenuItem x:Name="MenuItem_Item1" IsCheckable="True" Header="item1" />
<MenuItem x:Name="MenuItem_Item2" IsCheckable="True" Header="item2"/>
<MenuItem x:Name="MenuItem_Item3" IsCheckable="True" Header="item3"/>
</MenuItem>
In XAML, is there a way to create checkable menuitem's that are mutually exclusive? Where is the user checks item2, item's 1 and 3 are automatically unchecked.
I can accomplish this in the code behind by monitoring the click events on the menu, determining which item was checked, and unchecking the other menuitems. I'm thinking there is an easier way.
Any ideas?
This may not be what you're looking for, but you could write an extension for the
MenuItem
class that allows you to use something like theGroupName
property of theRadioButton
class. I slightly modified this handy example for similarly extendingToggleButton
controls and reworked it a little for your situation and came up with this:Then, in the XAML, you'd write:
It's a bit of a pain, but it offers the perk of not forcing you to write any additional procedural code (aside from the extension class, of course) to implement it.
Credit goes to Brad Cunningham who authored the original ToggleButton solution.
Simply create a Template for MenuItem which will contain a RadioButton with a GroupName set to some value. You can also change the template for the RadioButtons to look like the MenuItem's default check glyph (which can be easily extracted with Expression Blend).
That's it!
Here's another approach that uses RoutedUICommands, a public enum property, and DataTriggers. This is a pretty verbose solution. I unfortunately don't see any way of making the Style.Triggers smaller, because I don't know how to just say that the Binding Value is the only thing different? (BTW, for MVVMers this is a terrible example. I put everything in the MainWindow class just to keep things simple.)
MainWindow.xaml:
MainWindow.xaml.cs:
Here's a simple, MVVM-based solution that leverages a simple IValueConverter and CommandParameter per MenuItem.
No need to re-style any MenuItem as a different type of control. MenuItems will automatically be deselected when the bound value doesn't match the CommandParameter.
Bind to an int property (MenuSelection) on the DataContext (ViewModel).
Define your value converter. This will check the bound value against the command parameter and vice versa.
Add your resource
Good luck!
There is not a built-in way to do this in XAML, you will need to roll your own solution or get an existing solution if available.
I just thought I would throw in my solution, since none of the answers met my needs. My full solution is here...
WPF MenuItem as a RadioButton
However, the basic idea is to use ItemContainerStyle.
And the following event click should be added so that the RadioButton is checked when the MenuItem is clicked (otherwise you have to click exactly on the RadioButton):