If you edit the TreView's style, you could find that in its ControlTemplate, it actually uses a TreeViewList control.
<Style x:Key="TreeViewStyle1" TargetType="TreeView">
<Setter Property="IsTabStop" Value="False"/>
<Setter Property="CanDragItems" Value="True"/>
<Setter Property="CanReorderItems" Value="True"/>
<Setter Property="AllowDrop" Value="True"/>
<Setter Property="ItemContainerTransitions">
<Setter.Value>
<TransitionCollection>
<ContentThemeTransition/>
<ReorderThemeTransition/>
<EntranceThemeTransition IsStaggeringEnabled="False"/>
</TransitionCollection>
</Setter.Value>
</Setter>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="TreeView">
<TreeViewList x:Name="ListControl" AllowDrop="{TemplateBinding AllowDrop}" CanReorderItems="{TemplateBinding CanReorderItems}" CanDragItems="{TemplateBinding CanDragItems}" ItemContainerStyleSelector="{TemplateBinding ItemContainerStyleSelector}" ItemContainerStyle="{TemplateBinding ItemContainerStyle}" ItemTemplate="{TemplateBinding ItemTemplate}" ItemContainerTransitions="{TemplateBinding ItemContainerTransitions}" ItemTemplateSelector="{TemplateBinding ItemTemplateSelector}"/>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
The TreeViewList class inherits from ListView
. The ListView has SelectedItem property.
So, you could make a custom TreeView control which inherits TreeView class. Then, you could find the TreeViewList control by calling its GetTemplateChild()
method. After that, you could set the selectedItem for it.
Please check my code sample:
public class MyTreeView:TreeView
{
TreeViewList treeViewList;
public MyTreeView()
{
this.Loaded += MyTreeView_Loaded;
}
private void MyTreeView_Loaded(object sender, Windows.UI.Xaml.RoutedEventArgs e)
{
if (treeViewList != null)
{
treeViewList.SelectedIndex = 0;
}
}
protected override void OnApplyTemplate()
{
base.OnApplyTemplate();
treeViewList = this.GetTemplateChild("ListControl") as TreeViewList;
}
}
But with this way, you could only set the selectedItem for the RootNodes. If you want to selecte the sub node, I still think the binding on the IsSelected
property is the better way.