Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create Event Handler for TreeViewItem in WPF

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>

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

like image 962
0x49D1 Avatar asked Jan 22 '23 06:01

0x49D1


1 Answers

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>

Code Behind:

private void OnTreeViewSelectedItemChanged( object sender, RoutedPropertyChangedEventArgs<object> e )
{
    MyTextBlock.Text = ( (TreeViewItem) ( (TreeView) sender ).SelectedItem ).Header.ToString();
}
like image 64
Metro Smurf Avatar answered Feb 03 '23 19:02

Metro Smurf