2010-10-21 83 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

相關問題