Search code examples
c#wpftreeviewselecteditemright-click

Select a TreeViewItem on Right-Click


I would like to be able to select a TreeViewItem in my program on right-click. Previously, (In this question) I tried to do this by calling to SetSelectedItem() method from wherever I wanted to allow a TreeViewItem to be selected. The answer from that question compiled and ran, but did not actually allow the TreeViewItem to become selected like I wanted.

This question that I've been looking at is pretty much the exact same question as this one, with the exception of the hierachicalDataTemplate. My TreeView does not have a hierachicalDataTemplate, and if it is unnecessary for my program I would like to avoid it.

This is what I have compiling, but not affecting change right now...

//Sets selected item in TreeView and passes to MainWindowViewModel
private void SetSelectedItem()
{
       MainWindowViewModel.SelectedItem = Tree_One.SelectedItem as TreeViewItem;
}

//**** This is the function this question is about -- It's Supposed to select item on RightClick
private void Tree_One_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
{
       SetSelectedItem();    
}

So just for clarity, the node that I right click does not get selected like expected. What am I doing wrong and how can I fix it?

UPDATE:

I think I know what the problem is after playing around with the answer below. The code I have in this question doesn't actually change the selected item, it just kind of reiterates through the selection of the currently selected item, re-selecting it. If there was a way to actually change the selected item to the item that is right clicked, it would run perfectly. Any clue on how to do something like that?


Solution

  • The answer by @alex2k8 on this question is exactly what I was looking for, and is what I used to solve my problem.

    Thanks to anyone who helped out.