0

我正在开发一个 WPF 项目,并且我已经向它添加了一个 TreeView。我还ContextMenu为 TreeView 创建了一个,如下所示:

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

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

.... </TreeView>

由于我动态地添加了 treeView 节点,我如何检测右键单击哪个节点以打开 contextMenu?

希望有人可以帮助我,在此先感谢

4

1 回答 1

1

假设我动态加载了我的树视图项目..

  <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>

主窗口.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());
        }

如果您想知道 ContextMenu关闭/打开时的对象,或者 MenuItem 被Clicked时的任何事件,这取决于您。

于 2012-08-07T20:01:15.860 回答