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?
You can also use a Behavior. Like this one:
Since there is not a samilar answer, I post my solution here:
In XAML just use it as an usual MenuItem:
Quite simple and clean. And of course you can make the
GroupName
a dependency property by some additional codes, that's all the same as others.BTW, if you do not like the check mark, you can change it to whatever you like:
If you used plenty of this
RadioMenuItem
in your program, there is another more efficient version shown below. The literal data is aquired frome.GetFlattenedPathGeometry().ToString()
in previous code snippet.And at last, if you plan to wrap it for use in your project, you should hide
IsCheckable
property from the base class, since the auto check machenism ofMenuItem
class will lead the radio check state mark a wrong behavior.Thus VS will give an error if a newbie try to compile XAML like this:
You could do something like this:
It has some weird side effect visually (you'll see when you use it), but it works nonetheless
I achieved this using a couple of lines of code:
First declare a variable:
When we are considering a group of menuitems, there is a probability of using a single event handler. In this case we can use this logic: