wpf 如何根据条件在wpf xaml中隐藏上下文菜单的菜单项
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31308846/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to hide the menu item of context menu in wpf xaml based on condition
提问by Tarun
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.
在我的 xaml 中,我使用 wpf ContextMenu 来显示 wpf datagid 中的菜单项。我需要根据条件隐藏菜单项。我尝试了以下但它不工作。
<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
谢谢
回答by eran otzap
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.
1) 是 ContextMenu 不与它设置的元素驻留在同一个 VisualTree 中(即它是 PlacementTarget)。因为您将无法绑定到具有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.
2)你把你的风格当作菜单项的内容。(我一开始也没有注意到它......)。它需要设置为您的 MenuItem 的 DependencyProperty 'Style'。
<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>

