Monday, July 20, 2009

Setting the selected treeItem in a treeview on right click

So over the past several weeks I have been working with a lot of TreeViews in WPF I use a HierarchicalDataTemplate with a custom ItemContainerStyle for my nodes in the tree. I have been having a rather hard time finding a way to easily set the right clicked on node before the context menu is opened on it. My HierarchicalDataTemplate consists of a stackpanel with a context menu and a image and textblock.

In the ContextMenu_Opened function i put the following code.

   93 var cMenu = sender as ContextMenu;
   94             var tbase = (cMenu.PlacementTarget as StackPanel).DataContext as BasicTreeViewBase;
   95             tbase.IsSelected = true;

Which will set my selected item to true. The BasicTreeViewBase is a ViewModdle object baised off of the code found at TreeViewWithViewModel and is rather simple.

No comments: