2010-10-21 82 views
5

我正在使用TreeView在UI中显示我的数据。现在我的应用程序每5秒刷新一次,以显示最新的数据。即使在窗口重新加载后,我是否可以保存我的展开状态或折叠状态的树状视图?因为如果我有大量的数据,并且需要超过5秒的时间才能找到所需的数据,那么TreeView会在每5秒刷新一次窗口后崩溃,我必须从头开始。在数据重新加载时保存WPF TreeView状态

 <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); 
     } 
     } 
+0

你重新创建Sections集合每5秒? – Rachel 2010-10-21 19:00:55

+0

是的..窗口每5秒重新加载/刷新一次。所以我把它当作一个可观察的集合,被清除,然后用对象填充。 – developer 2010-10-21 19:24:32

+0

哦,那么你的IsExpanded属性也每5秒清除一次。你有可能只更新值而不是删除它们并重新创建它们? – Rachel 2010-10-21 19:25:48

回答

13

我解决了这个问题,通过增加IsExpanded和IsSelected属性的对象,我的TreeView注定要

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

我在后面的代码中写什么? – developer 2010-10-21 16:22:36

+0

另外,我将如何为每个节点设置IsExpanded的值。 – developer 2010-10-21 16:44:56

+2

这取决于您的TreeView绑定的内容。如果它是自定义对象的列表,那么很容易,只需添加两个名为IsExpanded和IsSelected的公共布尔属性。设置它们你不需要做任何事情。他们将默认为False并在用户展开/折叠/选择树视图项目时得到更新,因为它使用的是双向绑定 – Rachel 2010-10-21 16:53:27

相关问题