我不想使用一些数据绑定对象来隐藏/显示上下文菜单中的菜单项。 但是我的菜单没有隐藏,它们的行为就好像它们的Visiblity被设置为Visibility.Hidden(不是Visibility.Collapsed,因为它确实存在),这种行为的原因是什么?
以下是一个例子:
XAML:
<Window x:Class="MenuTest.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window">
<Window.Resources>
<BooleanToVisibilityConverter x:Key="converter"/>
<DataTemplate x:Key="template">
<MenuItem Visibility="{Binding Visible, Converter={StaticResource converter}}" Header="{Binding Title}" />
</DataTemplate>
<ContextMenu x:Key="menu" ItemTemplate="{StaticResource template}"/>
</Window.Resources>
<Grid>
<Button VerticalAlignment="Center" HorizontalAlignment="Center" Click="OnClick">Button</Button>
</Grid>
</Window>
代码背后:
public partial class Window1 : Window
{
public ObservableCollection<Item> list = new ObservableCollection<Item>();
public Window1()
{
InitializeComponent();
list.Add(new Item() { Title = "First", Visible = true }); ;
list.Add(new Item() { Title = "Second", Visible = false }); ;
list.Add(new Item() { Title = "Third", Visible = false }); ;
list.Add(new Item() { Title = "Fourth", Visible = true }); ;
}
private void OnClick(object sender, RoutedEventArgs e)
{
ContextMenu cm = FindResource("menu") as ContextMenu;
cm.PlacementTarget = e.OriginalSource as UIElement;
cm.Placement = System.Windows.Controls.Primitives.PlacementMode.Left;
cm.ItemsSource = list;
cm.IsOpen = true;
}
}
public class Item
{
public string Title { get; set; }
public bool Visible { get; set; }
}
结果是包含四个项目的菜单(但中间有两个项目,标题中没有任何可见文本)。
答案 0 :(得分:3)
此行为是因为ContextMenu的ItemTemplate将应用于为该项创建的MenuItem中中的每个绑定项。通过将MenuItem放入DataTemplate,可以创建嵌套的MenuItem。即使你折叠了内部的那个,因为外部的一个仍然是可见的,它仍然有空间。
您可以通过删除DataTemplate中的嵌套MenuItem并将其替换为TextBlock,并使用适用于MenuItem的Style来设置可见性来解决此问题:
<Window x:Class="MenuTest.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window">
<Window.Resources>
<BooleanToVisibilityConverter x:Key="converter"/>
<DataTemplate x:Key="template">
<TextBlock Text="{Binding Title}"/>
</DataTemplate>
<ContextMenu x:Key="menu" ItemTemplate="{StaticResource template}">
<ContextMenu.Resources>
<Style TargetType="{x:Type MenuItem}">
<Setter Property="Visibility" Value="{Binding Visible, Converter={StaticResource converter}}"/>
</Style>
</ContextMenu.Resources>
</ContextMenu>
</Window.Resources>
<Grid>
<Button HorizontalAlignment="Center" VerticalAlignment="Center" Click="OnClick">Button</Button>
</Grid>
</Window>