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.
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With