Is there a way to specify in a TreeView's HierarchicalDataTemplate to use a different context menu depending on a property on the data an item is bound to? For instance, display one context menu if Item.IsFile is true, display a different one if Item.IsFolder is tree, etc.
+4
A:
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;
}
SMART_n
2009-11-20 09:32:14
seems pretty much perfect, thanks for the full example!
Jared
2009-11-21 17:56:44