I wan't to hide/show menuitems in a contextmenu using some propery of databound object. But my menuitems don't hide, they behave as if their Visiblity would be set to Visibility.Hidden (not Visibility.Collapsed as it really is), what's the reason of such behaviour?
Here's an example:
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>
And code behind:
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; }
}
The result is menu with four items (but two in the middle without any visible text in header).