C# · 12月 24, 2021

c# – TreeView.ItemContainerGenerator.ContainerFromItem为非根项目返回null.解决方法?

在下面的示例中,当我选择“String”时,窗口的标题变为“null”.但我必须获得“String”的容器.具体来说,我想做相当于SelectedItem = null(但该属性只读取TreeView,所以我试图到容器将其IsSelected设置为false).该怎么办? <Window x:Class=”WpfApplication1.Window1″ xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation” xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml”> <Window.Resources> <x:Array xmlns=”clr-namespace:System;assembly=mscorlib” x:Key=”Array” Type=”Object”> <x:ArrayExtension Type=”Object”> <String>String</String> </x:ArrayExtension> </x:Array> </Window.Resources> <TreeView ItemsSource=”{StaticResource Array}” SelectedItemChanged=”Handler”> <TreeView.ItemTemplate> <HierarchicalDataTemplate ItemsSource=”{Binding}”> <TextBlock Text=”Array”/> <HierarchicalDataTemplate.ItemTemplate> <DataTemplate> <TextBlock Text=”{Binding}”/> </DataTemplate> </HierarchicalDataTemplate.ItemTemplate> </HierarchicalDataTemplate> </TreeView.ItemTemplate> </TreeView> namespace WpfApplication1{ public partial class Window1 : Window { public Window1() { InitializeComponent(); } private void Handler(object sender,EventArgs e) { var treeView = sender as TreeView; var container = treeView.ItemContainerGenerator.ContainerFromItem(treeView.SelectedItem); Title = container != null ? container.ToString() : “null”; } }}解决方法 问题是每个TreeViewItem本身就是一个ItemsControl,所以他们每个人都为自己的孩子管理自己的容器.

但是,有一种非常简单的方法可以执行您想要执行的操作:注册到TreeViewItem.Selected事件,而不是注册到SelectedItemChanged事件,该事件将使用设置为所选TreeViewItem的OriginalSource冒泡.

XAML:

<TreeView ItemsSource=”{StaticResource Array}” TreeViewItem.Selected=”TreeViewItem_Selected”>

代码背后:

private void TreeViewItem_Selected(object sender,RoutedEventArgs e) { TreeViewItem container = (TreeViewItem) e.OriginalSource; Title = container != null ? container.ToString() : “null”;}