我不确定为什么没有在嵌套的 TreeViewItem 上处理 Selected 事件,但是如果我们稍微改变它以在 TreeView 上设置 ItemsSource,它确实会得到处理:
<controls:TreeView x:Name="tv" SelectedItemChanged="tv_SelectedItemChanged">
<controls:TreeView.ItemTemplate>
<DataTemplate>
<!-- this Selected event handler does get called -->
<controls:TreeViewItem Header="{Binding Name}" Selected="TreeViewItem_Selected" >
...
但是,引发的事件不包含有关该项目的任何有用信息,因此您无法明智地从该事件中得出任何有用的信息。
Setting a handler for the SelectedItemChanged event on the TreeView works and also contains the usual OldValue and NewValue properties in the EventArgs.
该事件也会为所有 TreeViewItems 触发 - 是否嵌套。
试试这个:
<controls:TreeView x:Name="tv" SelectedItemChanged="tv_SelectedItemChanged">
<controls:TreeViewItem x:Name="tvi" Header="RootNodeTitle" IsExpanded="True" Selected="TreeViewItem_Selected" >
<ItemsControl.ItemTemplate>
<DataTemplate>
<controls:TreeViewItem Header="{Binding}" Selected="TreeViewItem_Selected" >
<Border Background="Black" Height="25" Width="25" />
</controls:TreeViewItem>
</DataTemplate>
</ItemsControl.ItemTemplate>
</controls:TreeViewItem>
</controls:TreeView>
...
void MainPage_Loaded(object sender, RoutedEventArgs e)
{
tvi.ItemsSource = GetItems();
}
private IEnumerable GetItems()
{
for (int i = 0; i < 10; i++)
{
yield return i;
}
}
private void tv_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
{
var oldItem = e.OldValue;
var newItem = e.NewValue;
}