【发布时间】:2017-02-08 08:03:05
【问题描述】:
我正在使用 HierarchicalDataTemplate 动态构建我的 TreeView,但不知道如何从 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>
【问题讨论】:
标签: wpf header treeview selecteditem hierarchicaldatatemplate