Reputation: 221
In my xaml, I have used wpf ContextMenu to display the menu items in wpf datagid. I need to hide the menu items based on the condition. I tried the following but its not working.
<ContextMenu x:Key="contextMenuTextCell">
<MenuItem Name="copyDealContextMenu"
Header="Copy Deal"
Command="{Binding RelativeSource={RelativeSource AncestorType=DataGrid}, Path=DataContext.CopyDeal}"
CommandParameter="{Binding}">
<Style TargetType="{x:Type MenuItem}">
<Setter Property="Visibility" Value="Collapsed"></Setter>
<Style.Triggers>
<DataTrigger Binding="{ Binding ElementName= BlotGrid,Path=DataContext.ProductType }" Value="FXO">
<Setter Property="Visibility" Value="Visible"></Setter>
</DataTrigger>
</Style.Triggers>
</Style>
</MenuItem>
</ContextMenu>
How to hide the menu items in context menu?
Thanks
Upvotes: 3
Views: 10514
Reputation: 12533
There are 2 reason this did not work.
1) is that ContextMenu does not reside in the same VisualTree as the element it is set for ( i.e. it's PlacementTarget). There for you would not be able to bind to an element with ElementName.
2) you put your Style like it's a Content of the MenuItem. ( I didn't notice it at first as well..). it needs to be set to the DependencyProperty 'Style' of your MenuItem.
<Grid x:Name="BlotGrid" Background="Red">
<Grid.ContextMenu>
<ContextMenu>
<MenuItem Name="copyDealContextMenu"
Header="Copy Deal"
CommandParameter="{Binding}">
<MenuItem.Style>
<Style TargetType="{x:Type MenuItem}">
<Setter Property="Visibility" Value="Collapsed"></Setter>
<Style.Triggers>
<DataTrigger Binding="{Binding RelativeSource={RelativeSource AncestorType=ContextMenu},Path=PlacementTarget.DataContext.IsXXX}" Value="True">
<Setter Property="Visibility" Value="Visible"></Setter>
</DataTrigger>
</Style.Triggers>
</Style>
</MenuItem.Style>
</MenuItem>
</ContextMenu>
</Grid.ContextMenu>
</Grid>
Upvotes: 6