[英]WPF C#: How to get treeviewitem header from HierarchicalDataTemplate
I am using HierarchicalDataTemplate to build my TreeView dynamicaly and don't know how to get the header of the selected item from treeview. 我正在使用HierarchicalDataTemplate动态地构建我的TreeView,并且不知道如何从treeview获取所选项目的标题。
I tried to get it by the TreeViewItem.Selected event. 我试图通过TreeViewItem.Selected事件获取它。
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 但是'item.Header'是Node类型的
this is my XAML-code: 这是我的XAML代码:
<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>
Yes, the selected item will be one of the items in RootNodes. 是的,所选项目将是RootNodes中的项目之一。 Cast it to that type.
将其转换为该类型。
Node
, it seems to be. Node
,似乎是。 The header will be whatever property of that class you use for the header -- Name
, it looks like. 标头将是您用于标头的该类的任何属性
Name
,看起来像。
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
. Node
是绑定到TreeView
上ItemsSource
的集合中包含的类。 I've also included code demonstrating how to get the selected TreeViewItem
. 我还包括了演示如何获取所选
TreeViewItem
代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.