Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change context menu in WPF TreeView for data

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.

like image 733
Jared Avatar asked Nov 20 '09 07:11

Jared


1 Answers

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;
    }
like image 151
SMART_n Avatar answered Oct 03 '22 02:10

SMART_n