Is there a way to specify in a TreeView
's HierarchicalDataTemplate
to use a different ContextMenu
depending on a property on the data an item is bound to?
For instance, display one ContextMenu
if Item.IsFile
is true, display a different one if Item.IsFolder
is true, etc.
This is example for ListBox, I think you can easily modify it to work with TreeView.
XAML:
...
<Window.Resources>
<ContextMenu x:Key="FileContextMenu">
...
</ContextMenu>
<ContextMenu x:Key="DirContextMenu">
...
</ContextMenu>
<local:ItemToContextMenuConverter x:Key="ContextMenuConverter" />
</Window.Resources>
...
<ListBox x:Name="SomeList">
<ListBox.ItemTemplate>
<DataTemplate>
<Label Content="{Binding Path=Name}" ContextMenu="{Binding Converter={StaticResource ContextMenuConverter}}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Code:
class Item
{
public string Name { get; set; }
public bool IsFile { get; set; }
}
[ValueConversion(typeof(Item), typeof(ContextMenu))]
public class ItemToContextMenuConverter : IValueConverter
{
public static ContextMenu FileContextMenu;
public static ContextMenu DirContextMenu;
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
Item item = value as Item;
if (item == null) return null;
return item.IsFile ? FileContextMenu : DirContextMenu;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new Exception("The method or operation is not implemented.");
}
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
ItemToContextMenuConverter.FileContextMenu
= this.Resources["FileContextMenu"] as ContextMenu;
ItemToContextMenuConverter.DirContextMenu
= this.Resources["DirContextMenu"] as ContextMenu;
List<Item> items = new List<Item>();
items.Add(new Item() { Name = "First", IsFile = true });
items.Add(new Item() { Name = "Second", IsFile = false });
SomeList.ItemsSource = items;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With