wpf TreeView 双击事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24237716/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
TreeView double click event
提问by Yona
I want to define a double click even on a TreeView so that I will be able to know which item in the TreeView was selected and to get his title. The way I try to get it's title gets me "MyProject.MenuItem". How can I refer to the selected item on the tree, make sure it's not the root, and get it's title? What I did:
我想甚至在 TreeView 上定义双击,以便我能够知道 TreeView 中的哪个项目被选中并获得他的标题。我试图获得它的标题的方式让我“MyProject.MenuItem”。我如何引用树上的选定项目,确保它不是根,并获得它的标题?我做了什么:
<TreeView Name="trvMenu" HorizontalAlignment="Left" Height="312" VerticalAlignment="Top" Width="200" MouseDoubleClick="TreeView_MouseDoubleClick" >
<TreeView.ItemTemplate>
<HierarchicalDataTemplate DataType="{x:Type local:MenuItem}" ItemsSource="{Binding Items}">
<TextBlock Text="{Binding Title}" />
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
The MessageBox shows "MyProject.MenuItem", what I want to do is not show a messagebox, but to get the title of the selected treeview item, after checking it is not the root
消息框显示“MyProject.MenuItem”,我想要做的不是显示消息框,而是获取所选树视图项的标题,检查它不是根后
private void TreeView_MouseDoubleClick(object sender, RoutedEventArgs e)
{
if (sender is TreeViewItem)
if (!((TreeViewItem)sender).IsSelected)
return;
TreeViewItem tviSender = sender as TreeViewItem;
MessageBox.Show(trvMenu.SelectedItem.ToString());
}
采纳答案by Clemens
Change your double click handler like shown below. Instead of calling ToStringit accesses the Titleproperty of your MenuItemitem class.
更改您的双击处理程序,如下所示。而不是调用ToString它访问Title您的MenuItem项目类的属性。
private void TreeView_MouseDoubleClick(object sender, RoutedEventArgs e)
{
var menuItem = trvMenu.SelectedItem as MyProject.MenuItem;
if (menuItem != null)
{
MessageBox.Show(menuItem.Title);
}
}

