Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save WPF TreeView state on data reload

Tags:

c#

wpf

I am using TreeView to display my data in UI. Now my application refreshes every 5 seconds so that it shows the most current data. Is there a way I can save my expanded state or collapsed state of treeview even after window reload? Because if I have a huge amount of data and I take more than 5 seconds to go to desired data, the TreeView just collapses after every 5 seconds with window refresh, and I have to start from scratch.

      <TreeView ItemsSource="{Binding Sections}" Grid.Row="1"
          ItemTemplate="{StaticResource sectionTemplate}" >

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

    </TreeView>

public ObservableCollection<MyViewModel> =new ObservableCollection<MyViewModel>();

public bool IsExpanded
    {
      get { return (bool)GetValue(IsExpandedProperty); }
      set { SetValue(IsExpandedProperty, value); }
    }
    public static readonly DependencyProperty IsExpandedProperty = DependencyProperty.Register("IsExpanded", typeof(bool), typeof(MyViewModel));


 if (result.TotalResults > 0)
      {
        foreach (DomainObject obj in result.ResultSet)
        {
          AT myAT= (AT)obj;
          arrdep.Add(myAT);
        }
      }
like image 911
developer Avatar asked Oct 21 '10 15:10

developer


1 Answers

I solved that problem by adding IsExpanded and IsSelected properties to the object that my TreeView was bound to

<Style TargetType="{x:Type TreeViewItem}">
    <Setter Property="IsExpanded" Value="{Binding IsExpanded, Mode=TwoWay}" />
    <Setter Property="IsSelected" Value="{Binding IsSelected, Mode=TwoWay}" />
</Style>
like image 149
Rachel Avatar answered Oct 05 '22 11:10

Rachel