wpf 如何添加WPF treeView节点点击事件获取节点值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24880824/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 12:11:26  来源:igfitidea点击:

How to add WPF treeView Node Click event to get the node value

c#wpftreeview

提问by user3816352

I have a TreeViewin WPF. Now I want to get the TreeViewnode click event so that I can get the value of the node on which the user has clicked. Here is the Code:

我有一个TreeViewWPF。现在我想获取TreeView节点单击事件,以便我可以获取用户单击的节点的值。这是代码:

<Grid Height="258" Width="275">
    <TreeView Height="258" HorizontalAlignment="Left" Name="treeView1" VerticalAlignment="Top" Width="275">    
    </TreeView>
</Grid>

I have populated this TreeViewfrom the C# code. What event methode do I need to write into c# code to get the value of clicked node by the user in my c# code.

我已经TreeView从 C# 代码填充了它。我需要在 c# 代码中写入什么事件方法才能在我的 c# 代码中获取用户单击节点的值。

Please help me.

请帮我。

Here is the c#.

这是c#。

TreeViewItem treeItem = null;
treeItem = new TreeViewItem();
treeItem.Header = "Name";

Like this i have populated the TreeView

像这样我填充了 TreeView

回答by pushpraj

Since there is no Click event available for TreeViewItem or TreeView so here are possible workaround for the same

由于 TreeViewItem 或 TreeView 没有可用的 Click 事件,因此这里有可能的解决方法

you have two options from C# code

你有两个来自 C# 代码的选项

using MouseLeftButtonUpwhich will trigger every time the mouse left button is released on the item, which is similar to click

using MouseLeftButtonUpwhich 将在每次在 item 上释放鼠标左键时触发,类似于 click

    void preparemethod()
    {
        ...
        TreeViewItem treeItem = null;
        treeItem = new TreeViewItem();
        treeItem.Header = "Name";
        treeItem.MouseLeftButtonUp += treeItem_MouseLeftButtonUp;
    }

    void treeItem_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
    {
        //your logic here
    }

or use Selected as trigger, may not trigger if a selected element is clicked

或使用 Selected 作为触发器,如果​​单击所选元素可能不会触发

    void preparemethod()
    {
        ...
        TreeViewItem treeItem = null;
        treeItem = new TreeViewItem();
        treeItem.Header = "Name";
        treeItem.Selected += treeItem_Selected;
    }

    void treeItem_Selected(object sender, RoutedEventArgs e)
    {
        //your logic here
    }

in both of the approach the sender is the node which has been clicked. you can use as

在这两种方法中,发送者都是被点击的节点。你可以用作

example

例子

    void treeItem_Selected(object sender, RoutedEventArgs e)
    {
        TreeViewItem item = sender as TreeViewItem;
        //you can access item properties eg item.Header etc. 
        //your logic here 
    }