我不想使用数据绑定对象的某些属性在上下文菜单中隐藏/显示菜单项。但是我的菜单项并没有隐藏,它们的行为就好像它们的 Visibility 将设置为 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; }
}
结果是包含四个项目的菜单(但中间有两个,标题中没有任何可见文本)。