Thursday, August 19, 2010

Use Style to keep the WPF tree's selection state

< TreeView.Resources >
< Style TargetType="{x:Type TreeViewItem}" >
                     < Setter Property="IsExpanded" Value="{Binding IsExpanded, Mode=TwoWay}"/ >
                     < Setter Property="IsSelected" Value="{Binding IsSelected, Mode=TwoWay}"/ >
                  < /Style>
< / TreeView.Resources >

also need to put event handler:


private void OnTreeViewItemExpanded(object sender, RoutedEventArgs e)
        {
            TreeViewItem tvi = e.OriginalSource as TreeViewItem;
            tvi.IsSelected = true;
            if (tvi.IsExpanded)
                tvi.Focus();
        }

No comments: