One more article in my list of articles about tree view expanding.
This time I will use story board from code behind.
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>
Code:
using System.Windows; namespace TreeViewAutoExpand { using System; using System.Windows.Controls; using System.Windows.Media.Animation; public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void MyTreeView_Loaded(object sender, RoutedEventArgs e) { BooleanAnimationUsingKeyFrames bukf = new BooleanAnimationUsingKeyFrames(); Storyboard.SetTargetProperty(bukf, new PropertyPath(TreeViewItem.IsExpandedProperty)); Storyboard.SetTarget(bukf, MyTreeView); foreach (object item in MyTreeView.Items) { TreeViewItem currentContainer = (TreeViewItem)MyTreeView.ItemContainerGenerator.ContainerFromItem(item); if (currentContainer != null) { Storyboard.SetTarget(bukf, currentContainer); } } bukf.KeyFrames.Add(new DiscreteBooleanKeyFrame(false, KeyTime.FromTimeSpan(TimeSpan.FromSeconds(0.0)))); bukf.KeyFrames.Add(new DiscreteBooleanKeyFrame(true, KeyTime.FromTimeSpan(TimeSpan.FromSeconds(2.0)))); Storyboard myStoryboard = new Storyboard(); myStoryboard.Children.Add(bukf); myStoryboard.Begin(); } } }
Point of interest:
foreach (object item in MyTreeView.Items) { TreeViewItem currentContainer = (TreeViewItem)MyTreeView.ItemContainerGenerator.ContainerFromItem(item); if (currentContainer != null) { Storyboard.SetTarget(bukf, currentContainer); } }
This code I needed since I didn't know how to access tree view items from code behind.
Example download from here.