Reputation: 15772
I want to use a trigger
to automatically hide a MenuItem
which is disabled. If I use my style inside a particular MenuItem
like this it works -
<MenuItem
Command="{Binding RelativeSource={RelativeSource FindAncestor,
AncestorType={x:Type ContextMenu}},
Path=PlacementTarget.DataContext.ExportCommand}"
Header="Export...">
<MenuItem.Style>
<Style TargetType="{x:Type MenuItem}">
<Style.Triggers>
<Trigger Property="IsEnabled" Value="False">
<Setter Property="Visibility" Value="Collapsed" />
</Trigger>
</Style.Triggers>
</Style>
</MenuItem.Style>
</MenuItem>
but if I place the same style
in a ResourceDictionary
like this, then it doesn't work -
<Style x:Key="{x:Type MenuItem}" TargetType="{x:Type MenuItem}" >
<Style.Triggers>
<Trigger Property="IsEnabled" Value="False">
<Setter Property="Visibility" Value="Collapsed" />
</Trigger>
</Style.Triggers>
</Style>
I want to have this behavior for all my menu items and I don't want to put this style on every MenuItem
inside my ContextMenu
. Any Idea why it's not working?
Upvotes: 3
Views: 2655
Reputation: 3828
Style is automatically applied to all instances of target types only if it does not have x:Key
set (http://msdn.microsoft.com/en-us/library/ms745683.aspx). Is this your case?
Upvotes: 1
Reputation: 446
This seems to work. I have just tried it:
<Grid>
<Grid.Resources>
<Style x:Key="{x:Type MenuItem}" TargetType="MenuItem" >
<Setter Property="OverridesDefaultStyle" Value="False" />
<Setter Property="TextBlock.Foreground" Value="Blue" />
<Style.Triggers>
<Trigger Property="IsEnabled" Value="False">
<Setter Property="Visibility" Value="Collapsed" />
</Trigger>
</Style.Triggers>
</Style>
</Grid.Resources>
<TextBox Text="Hello!" IsReadOnly="True">
<TextBox.ContextMenu>
<ContextMenu >
<MenuItem Header="Item1" />
<MenuItem Header="Item2" IsEnabled="False"/>
<MenuItem Header="Item3" />
</ContextMenu>
</TextBox.ContextMenu>
</TextBox>
</Grid>
Upvotes: 1