I am using HierarchicalDataTemplate to build my TreeView dynamicaly and don't know how to get the header of the selected item from treeview.
I tried to get it by the TreeViewItem.Selected event.
private void TreeViewItem_OnItemSelected(object sender, RoutedEventArgs e)
{
TreeViewItem item = e.OriginalSource as TreeViewItem;
string name = item.Header.ToString();
}
but 'item.Header' is of type Node
this is my XAML-code:
<Window x:Class="MaschinenStoppScheduler.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:MyNamespace="clr-namespace:MaschinenStoppScheduler"
Title="MaschinenStoppScheduler" Height="500" Width="900" Loaded="Window_Loaded_1">
<Window.DataContext>
<MyNamespace:MainWindowVM />
</Window.DataContext>
<Grid>
<TreeView x:Name="TreeViewGroups" TreeViewItem.Selected ="TreeViewItem_OnItemSelected"
ItemsSource="{Binding RootNodes}" HorizontalAlignment="Left" Margin="20,28,0,25"
VerticalAlignment="Stretch" Width="181" SelectedItemChanged="TreeViewGroups_SelectedItemChanged">
<ItemsControl.ItemContainerStyle>
<Style
TargetType="{x:Type TreeViewItem}">
<Setter Property="IsExpanded" Value="{Binding IsExpanded}" />
</Style>
</ItemsControl.ItemContainerStyle>
<ItemsControl.ItemTemplate>
<HierarchicalDataTemplate DataType="{x:Type MyNamespace:Node}" ItemsSource="{Binding Children}">
<StackPanel Orientation="Horizontal" HorizontalAlignment="Left">
<TextBlock Text="{Binding Name}" />
</StackPanel>
</HierarchicalDataTemplate>
</ItemsControl.ItemTemplate>
</TreeView>
</Grid>