我有一个上下文菜单,通过数据绑定获取菜单项 (我使用MVVM模式):
<ContextMenu ItemsSource="{Binding Path=ContextMenuItems}" />
这个方法运行良好。但是,当没有菜单项可显示时,在任何情况下我都不想出现上下文菜单。有没有办法实现这一点?可能是某种XAML触发器吗?
我尝试在打开事件中捕获和关闭上下文菜单,当没有子元素时关闭它。这样可以工作,但上下文菜单仍会闪烁...
我有一个上下文菜单,通过数据绑定获取菜单项 (我使用MVVM模式):
<ContextMenu ItemsSource="{Binding Path=ContextMenuItems}" />
这个方法运行良好。但是,当没有菜单项可显示时,在任何情况下我都不想出现上下文菜单。有没有办法实现这一点?可能是某种XAML触发器吗?
我尝试在打开事件中捕获和关闭上下文菜单,当没有子元素时关闭它。这样可以工作,但上下文菜单仍会闪烁...
您可以定义一个隐式样式:
<Style TargetType="{x:Type ContextMenu}">
<Style.Triggers>
<Trigger Property="HasItems" Value="False">
<Setter Property="Visibility" Value="Collapsed" />
</Trigger>
</Style.Triggers>
</Style>
这应该适用于你所有的上下文菜单。
可能绑定到您的菜单项集合计数属性,并使用转换器来设置上下文菜单的可见性。
<ContextMenu ItemsSource="{Binding Path=ContextMenuItems}"
Visibility="{Binding Path=ContextMenuItems.Count,Converter={StaticResource zeroToHiddenConverter}}">
public class ZeroToHiddenConverter:IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
int count = (int) value;
if (count == 0)
{
return Visibility.Hidden;
}
else
{
return Visibility.Visible;
}
}
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<BooleanToVisibilityConverter x:Key="VisibilityOfBool" />
<Style TargetType="{x:Type ContextMenu}">
<Setter Property="Visibility" Value="{Binding HasItems, RelativeSource={RelativeSource Self}, Converter={StaticResource VisibilityOfBool}}"/>
</Style>
</ResourceDictionary>
protected override void OnContextMenuOpening(ContextMenuEventArgs e) {
var item = FindTreeViewItem(e.OriginalSource as DependencyObject);
var contextMenu = item.ContextMenu;
if (contextMenu != null && !contextMenu.HasItems) {
e.Handled = true;
}
}
private TreeViewItem FindTreeViewItem(DependencyObject dependencyObject) {
if (dependencyObject == null) {
return null;
}
var treeViewItem = dependencyObject as TreeViewItem;
if (treeViewItem != null) {
return treeViewItem;
}
return FindTreeViewItem(VisualTreeHelper.GetParent(dependencyObject));
}