如何为ENUM类型通过XAML孩子设置菜单项的财产器isChecked?何为、菜单项、财产、类型

2023-09-03 01:44:38 作者:敗者王战

我一直使用这种解决方案绑定一个菜单项到一个枚举。

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.

我已经试过以下code,使用样式和触发二传手:

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>

枚举包含的值,例如意达,我也试着 AnEnum.First 0 在触发Value属性(如这里回答),但没有成功。

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.

一会 DataTrigger 可取?如果是这样,我怎么能写在XAML? 或者我应该使用的DataTemplate ItemTemplate中菜单项

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 ?

我也试着在code-身后 SomeSetting.Items 摆弄周围产权相关的方法,但大部分属性(如电流)读-只要。

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.

据我所知,你可以写 SomeSettingMenu.ItemsSource = Enum.GetValues​​(typeof运算(....))在code-背后,却再次我不知道如何在菜单项中选择一个项目编程。

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.

我也试过这个code,不能正常工作还有:

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.

任何想法将AP preciated,谢谢你在前进!

Any thoughts would be appreciated, thank you in advance !

推荐答案

在您的解决方案考虑更改

in your solution consider changing

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

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

在你的榜样,你检查头等于刺枚举:AnEnum.ItemA不枚举AnEnum成员意达

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