How can I bind the Visibility property on a top level MenuItem to a ViewModel
I’m using the following HierarchicalDataTemplate to bind a collection of MenuViewModels to a Menu control:
<HierarchicalDataTemplate
DataType="{x:Type common:MenuViewModel}"
ItemsSource="{Binding Path=Children}">
<HierarchicalDataTemplate.ItemContainerStyle>
<Style TargetType="MenuItem">
<Setter Property="Command" Value="{Binding Command}"/>
<Setter Property="开发者_运维技巧Visibility" Value="{Binding IsVisible, Converter={StaticResource ResourceKey=boolToCollapsedConverter}}" />
</Style>
</HierarchicalDataTemplate.ItemContainerStyle>
<ContentPresenter
Content="{Binding Name}"
RecognizesAccessKey="True" />
</HierarchicalDataTemplate>
This is all working fine, however I have a requirement to remove certain menu items based on particular states (for example, I might only want to show an ‘Edit’ top level menu if the edit screen is active) To achieve this I have an IsVisible property on the MenuViewModel, which in turn is bound via a booleanToVisibility converter to the MenuItem’s Visibility property (Set in the HierarchialDataTameplate.ItemContainerStyle, which I think is where my problem lies)
This works fine on child menu items, but has no affect on top level menu items.
I’ve knocked up a quick example showing the problem here (VS2010 .sln)
My question is: How can I bind the visibility property on a top level MenuItem to a ViewModel?
<Style x:Key="MenuItemStyle" TargetType="{x:Type MenuItem}">
<Setter Property="Command" Value="{Binding Command}"/>
<Setter Property="Visibility" Value="{Binding IsVisible, Converter={StaticResource ResourceKey=boolToCollapsedConverter}}" />
</Style>
snip...
<Menu DockPanel.Dock="Top" ItemsSource="{Binding Path=MainMenu}" ItemContainerStyle="{DynamicResource MenuItemStyle}"/>
You need to apply the style at a higher level, e.g. Menu.ItemContainerStyle
, this should only affect the top level though, so if you want to affect all items apply it implicitly via the Style.TargetType
through the Menu.Resources
.
精彩评论