在WPF中为TreeViewItem创建事件处理程序

在WPF中为TreeViewItem创建事件处理程序

本文介绍了在WPF中为TreeViewItem创建事件处理程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通过ItemsSource属性和ItemTemplate属性将项目添加到TreeView控件中,以设置TreeViewItem的模板.如何添加事件处理程序以处理TreeViewItems上的选择更改事件?
现在,我的ItemTemplate看起来像这样:

Im adding items to TreeView control via ItemsSource property and ItemTemplate property to set the template for TreeViewItem. How can i add an event handler to handle selection change event on TreeViewItems?
For now my ItemTemplate looks like this:

<Window.Resources><DataTemplate x:Key="PeerDetailTemplate">
        <TextBlock Text="{Binding DESCRIPTION}" Tag="{Binding ID}" GotFocus="GetModules"/>
</DataTemplate></Window.Resources>

但是它不起作用(未调用GetModules).我对WPF还是陌生的,所以请告诉我正确的方向来做这样的事情.

But it doesnt work (GetModules is not called). Im new to WPF, so show me the right direction to do such things, please.

推荐答案

如果要捕获 SelectedItemChanged 事件"rel =" noreferrer> TreeView ,那么您需要在父节点上设置事件处理程序,即

If you want to capture the SelectedItemChanged event in a TreeView, then you need to set the event handler on the parent node, i.e.,

XAML

<StackPanel>
    <TreeView SelectedItemChanged="OnTreeViewSelectedItemChanged">
        <TreeViewItem Header="Desktop">
            <TreeViewItem Header="Computer" />
            <TreeViewItem Header="My Documents" />
            <TreeViewItem Header="c:\" />
        </TreeViewItem>
        <TreeViewItem Header="Recyle Bin" >
            <TreeViewItem Header="foo.txt" />
            <TreeViewItem Header="bar.txt" />
            <TreeViewItem Header="fizz.buzz" />
        </TreeViewItem>
        <TreeViewItem Header="Control Panel" >
            <TreeViewItem Header="Programs" />
            <TreeViewItem Header="Security" />
            <TreeViewItem Header="User Accounts" />
        </TreeViewItem>
    </TreeView>

    <TextBlock Margin="20" x:Name="MyTextBlock" />
</StackPanel>

隐藏代码:

private void OnTreeViewSelectedItemChanged( object sender, RoutedPropertyChangedEventArgs<object> e )
{
    MyTextBlock.Text = ( (TreeViewItem) ( (TreeView) sender ).SelectedItem ).Header.ToString();
}

这篇关于在WPF中为TreeViewItem创建事件处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 06:23