我正在使用HierarchicalDataTemplate动态构建我的TreeView,并且不知道如何从树视图中获取所选项目的标题。
我试图通过TreeViewItem.Selected事件获取它。
private void TreeViewItem_OnItemSelected(object sender, RoutedEventArgs e)
{
TreeViewItem item = e.OriginalSource as TreeViewItem;
string name = item.Header.ToString();
}
但' item.Header'属于Node
类型这是我的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>
答案 0 :(得分:0)
是的,所选项目将是RootNodes中的项目之一。把它投射到那种类型。 Node
,似乎是。标题将是您用于标题的类的任何属性 - 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
是您绑定到ItemsSource
TreeView
的集合中包含的类。我还提供了演示如何获取所选TreeViewItem
的代码。