Dante
Dante

Reputation: 3316

Detect what TreeView node was right-clicked

I am working on a WPF project and I have added a TreeView to it. I have also created a ContextMenu to the TreeView as below:

<TreeView Name="treeView" ItemsSource="{Binding Elements}">

                <TreeView.ContextMenu>
                    <ContextMenu Name="treeViewContextMenu">
                        <MenuItem Header="First option"/>
                        <MenuItem Header="Second Option/>
                    </ContextMenu>
                </TreeView.ContextMenu>

.... </TreeView>

Since I add the treeView nodes dinamically, how can I detect what node was right-clicked in order to open the contextMenu?

Hope someone can help me, thanks in advance

Upvotes: 0

Views: 405

Answers (1)

123 456 789 0
123 456 789 0

Reputation: 10865

Assuming that I loaded my treeview item's dynamically..

  <TreeView Name="treeView" ContextMenuClosing="treeView_ContextMenuClosing">

    <TreeView.ContextMenu>
        <ContextMenu Name="treeViewContextMenu">
            <MenuItem Header="First option"/>
                <MenuItem Header="Second Option"/>
            </ContextMenu>
     </TreeView.ContextMenu>
        <TreeViewItem Header="Hello 1"/>
        <TreeViewItem Header="Hello 2"/>
     </TreeView>

MainWindow.xaml.cs

private void treeView_ContextMenuClosing(object sender, ContextMenuEventArgs e)
        {
           //Sender should let me determine who sent it from my children/parent

            var parent  = sender as TreeView;
            var children = parent.SelectedItem as TreeViewItem;
            MessageBox.Show(children.Header.ToString());
        }

It's up to you if you want to know the object when the ContextMenu is Closed/Open or whatever event like when the MenuItem is Clicked.

Upvotes: 1

Related Questions