I've bound a MenuItem to a Enum using this solution.
The Enum Values are displayed correctly, yet I cannot seem to set a default checked value for the MenuItem's children items.
Alternatively put, I would like the MenuItem to have one of its children items (the values of the enum I'm using) checked per default.
I've tried the following code, using a Style and a triggered Setter :
<ContextMenu>
<MenuItem Header="Some Setting" Name="SomeSettingMenu" DataContext="{Binding}"
ItemsSource="{Binding Source={StaticResource DisplayTypeValues}}"
Click="SomeSettingClicked">
<MenuItem.ItemContainerStyle>
<Style TargetType="MenuItem">
<Setter Property="MenuItem.IsCheckable" Value="True"/>
<Style.Triggers>
<Trigger Property="MenuItem.Header" Value="enums:AnEnum.ItemA" >
<Setter Property="MenuItem.IsChecked" Value="True"/>
</Trigger>
</Style.Triggers>
</Style>
</MenuItem.ItemContainerStyle>
</MenuItem>
</ContextMenu>
The enum contains values such as ItemA, I've also tried AnEnum.First
or 0
in the Trigger Value attribute (as answered here), to no avail.
Would a DataTrigger
be advisable ? If so, how can I write that in XAML ?
Or should I use an DataTemplate
within an ItemTemplate
for the MenuItem
?
I've also tried fiddling around in code-behind with SomeSetting.Items
-related methods, yet most of the properties (such as Current) are read-only.
I am aware that you can write SomeSettingMenu.ItemsSource = Enum.GetValues(typeof(....))
in code-behind, but yet again I don't know how to select an Item within the MenuItem programmatically.
I've also tried this code, doesn't work as well :
<Style.Triggers>
<DataTrigger Binding="{Binding Path=Header}" Value="enums:DisplayType.ItemA">
<Setter Property="IsChecked" Value="True" />
</DataTrigger>
</Style.Triggers>
enums
is a namespace from a different assembly I'm using.
Any thoughts would be appreciated, thank you in advance !
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…