views:

121

answers:

1

I've given my WPF ListView a context menu:

<TreeView ContextMenuOpening="TreeView_ContextMenuOpening">
    <TreeView.ContextMenu>
        <ContextMenu>
            <MenuItem Name="NewInputMenuItem" Header="Add" Click="AddInputMenuItem_Click" />
            <MenuItem Name="RemoveInputMenuItem" Header="Remove" Click="RemoveInputMenuItem_Click" />
        </ContextMenu>
    </TreeView.ContextMenu>
    <!-- etc... -->
</TreeView>

I've defined the context menu on theTreeView rather than the TreeViewItem as I want the same context menu displayed regardless of whether or not an item is selected, however I do want the "Remove" menu item to be enabled only if the user has right clicked on an item, not just on empty space in the menu.

The way that I'm currently handling this is to use the selected item property of the TreeView (in the TreeView_ContextMenuOpening event handler), however the problem is that right clicking on a tree view item opens the context menu for that tree view without changing the selected state of the tree view item.

Also, I can't help but think that all of the above is very un WPF-like, so:

  • How can I make it so that when the user right clicks on a tree view item, that item is selected.
  • And is there a better way of achieving the above?
A: 

WPF Commands are very usefull in this situation. i think you better bind each of your MenuItem to a command. this way in each command you can define when this command can be excuted. WPF automaticaly check if each command can be excuted at runtime. if any of them does not allowed to be excuted them the binded control to that command will automatically become disabled. here you can use this sample code as your CanExcute method for the remove command of the treeview:

private bool CanExcute()
{
    if (MyTreeView.SelectedItem != null)
       return true;
    else
       return false;
}

by doing this, only after an item had been selected, the remove command would be enabled. otherwise its menu item will become disabled.

Nima Rikhtegar