Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
618 views
in Technique[技术] by (71.8m points)

c# - How to set a MenuItem's IsChecked property for a child of type Enum via XAML?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

in your solution consider changing

<Trigger Property="MenuItem.Header" Value="enums:AnEnum.ItemA" >

to

<Trigger Property="MenuItem.Header" Value="{x:Static enums:AnEnum.ItemA}" >

in your example you check that header is equal to sting "enums:AnEnum.ItemA" not to enum AnEnum member ItemA.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...