Friday, April 18, 2008 8:26 AM
I'm currently looking for a simple code to "graphically" select an item on a TreeView with a right click. Usually, when we right-click an item, the contextual menu pops up but the item does not appear to be selected.
Now, I would like the user to be able to see which item has been selected in the TreeView...
Sunday, April 20, 2008 10:59 PM
Just add a MouseRightButtonDown event handler to each TreeViewItem and use the sender parameter to set the TreeViewItem's IsSelected property to true. You can even use a Style to make sure that the event handler gets attached:Code SnippetCode Snippet
private void TreeViewItem_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
((TreeViewItem)sender).IsSelected = true;
Hope this helps,
Wells Caughey | Magenic Technologies
Monday, April 21, 2008 8:00 AMOk it works. Thanks a lot !
Monday, April 21, 2008 8:12 AMBe careful, I found in an application Im working on, when you programmatically select the treeviewitem on the right mouse button handler, the context menu can pop up before the treeviewitem is selected, even though it visually appears to be selected.
So what you get is the misleading visual appearance of a new node being selected, a context menu showing, but inside the context menu event handlers, it things the old node is still selected.
Run a quick check in your context menu event handlers that the node you think is selected is the right one!
Tuesday, April 22, 2008 6:57 AMThank you very much for this warning Andy !
Friday, August 01, 2008 12:20 AMAndyB1979 said:
...when you programmatically select the treeviewitem on the right mouse button handler, the context menu can pop up before the treeviewitem is selected, even though it visually appears to be selected.
Using PreviewMouseRightButtonDown instead of MouseRightButtonDown might solve this problem.
FYI for others out there: I found some strange tree behavior after programatically setting IsSelected on a TreeViewItem. The behavior seemed to be fixed by calling Focus() on the TreeViewItem after setting IsSelected.