0
votes

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>

1

1 Answers

0
votes

Yes, the selected item will be one of the items in RootNodes. Cast it to that type. Node, it seems to be. The header will be whatever property of that class you use for the header -- Name, it looks like.

private void TreeView_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
{
    var treeView = sender as TreeView;

    var selectedNode = treeView.SelectedItem as Node;

    TreeViewItem tvi = treeView.ItemContainerGenerator.ContainerFromItem(treeView.SelectedItem) as TreeViewItem;
}

Node is the class contained in the collection you bound to ItemsSource on the TreeView. I've also included code demonstrating how to get the selected TreeViewItem.