When you set ItemSource
the SelectedItem
corresponds to the DataContext
type as in your Type T
of the ItemSource
collection you set, not the actual TreeViewItem
.
hence why your cast fails.
Now when you create them in xaml directly without setting the ItemSource
, SelectedItem
is just the TreeViewitem
itself and the as
cast works fine.
Update:
It has nothing to with your DataTemplate
try this:
<Window.Resources>
<x:Array x:Key="someArray"
Type="sys:String">
<sys:String>Hello</sys:String>
<sys:String>World</sys:String>
</x:Array>
</Window.Resources>
<StackPanel>
<TreeView x:Name="MyTreeView"
ItemsSource="{DynamicResource someArray}" />
<Button Click="ButtonBase_OnClick"
Content="Some" />
</StackPanel>
and code-behind:
private void ButtonBase_OnClick(object sender, RoutedEventArgs e) {
TreeViewItem selectedItem = MyTreeView.SelectedItem as TreeViewItem;
if (selectedItem != null) {
selectedItem.IsSelected = false;
MyTreeView.Focus();
} else {
Debug.WriteLine("Not TreeViewitem");
Debug.WriteLine(MyTreeView.SelectedItem);
}
}
now when app is run click on an item and then click the Button
check the output Window and you'll see
Not TreeViewitem
Hello
DataTemplate
merely helps visualize a custom Datatype in the View. This is intended behavior when a collection is bound to the TreeView
Solution:
in your case to get the Actual TreeViewItem
try:
private void ButtonBase_OnClick(object sender, RoutedEventArgs e) {
TreeViewItem selectedItem =
MyTreeView.ItemContainerGenerator.ContainerFromItem(MyTreeView.SelectedItem) as TreeViewItem;
if (selectedItem == null)
return;
selectedItem.IsSelected = false;
MyTreeView.Focus();
}
^^ this supposedly does not work for HierarchicalDataTemplate
. Refer to this for more options.