XAML:
<Window x:Class="TreeViewAutoExpand.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:viewModel="clr-namespace:TreeViewAutoExpand.ViewModel"
xmlns:model="clr-namespace:TreeViewAutoExpand.Model"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Grid.Resources>
<viewModel:TreeViewAutoExpandViewModel x:Key="TreeViewAutoExpandViewModel" />
</Grid.Resources>
<TreeView x:Name="MyTreeView" DataContext="{StaticResource TreeViewAutoExpandViewModel}" ItemsSource="{Binding TreeViewAutoExpandItems}" Loaded="MyTreeView_Loaded">
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding Children}" DataType="{x:Type model:TreeViewAutoExpandModel}">
<TreeViewItem x:Name="myTreeViewItem" Header="{Binding Name}"/>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
</Grid>
</Window>
Thing to notice:
<TreeView x:Name="MyTreeView" DataContext="{StaticResource TreeViewAutoExpandViewModel}" ItemsSource="{Binding TreeViewAutoExpandItems}" Loaded="MyTreeView_Loaded">
Code:
using System.Windows;
namespace TreeViewAutoExpand
{
using System.Windows.Controls;
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void ShowSelectedThing(ItemsControl parentContainer)
{
// check current level of tree
foreach (object item in parentContainer.Items)
{
TreeViewItem currentContainer = (TreeViewItem)parentContainer.ItemContainerGenerator.ContainerFromItem(item);
if (currentContainer != null)
{
currentContainer.IsExpanded = true;
}
}
}
private void MyTreeView_Loaded(object sender, RoutedEventArgs e)
{
ShowSelectedThing(MyTreeView);
}
}
}
Example you can download from here.