我正在开发一个WPF项目,我已经添加了一个TreeView。我还为TreeView创建了一个ContextMenu
,如下所示:
<TreeView Name="treeView" ItemsSource="{Binding Elements}">
<TreeView.ContextMenu>
<ContextMenu Name="treeViewContextMenu">
<MenuItem Header="First option"/>
<MenuItem Header="Second Option/>
</ContextMenu>
</TreeView.ContextMenu>
.... </TreeView>
由于我以dinamically方式添加treeView节点,如何检测右键单击哪个节点以打开contextMenu?
希望有人可以帮助我,提前谢谢
答案 0 :(得分:1)
假设我动态加载了我的treeview项目..
<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());
}
如果你想知道ContextMenu 关闭/打开 时的对象,或者当MenuItem 点击时的任何事件,这取决于你。 强>