2011-12-18 95 views
0

我使用的是具有HierarchicalDataTemplate的TreeView,但無法獲得比第一級更高級別的IsExpanded屬性。這是我的XAML:IsExpanded僅適用於TreeView的第一級

<TreeView> 
    <TreeView.ItemTemplate> 
     <HierarchicalDataTemplate ItemsSource="{Binding Children}"> 
      <TextBlock Text="{Binding Text}" /> 
     </HierarchicalDataTemplate> 
    </TreeView.ItemTemplate> 
</TreeView> 

在我的ResourceDictionary我:

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

什麼使一級工作。

在更高的縮進級別IsExpanded始終爲false,因爲PropertyChangedEventHandler未針對子級觸發。

這裏是我的類:

public class ListItem : INotifyPropertyChanged 
{ 
    private bool isExpanded; 
    public bool IsExpanded 
    { 
     get { return isExpanded; } 
     set 
     { 
      if (isExpanded != value) 
      { 
       isExpanded = value; 
       SendPropertyChanged("IsExpanded"); 
      } 
     } 
    } 
    private void SendPropertyChanged(string propertyName) 
    { 
     if (PropertyChanged != null) 
     { 
      PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); 
     } 
    } 

    public event PropertyChangedEventHandler PropertyChanged; 

    public ObservableCollection<ListItem> Children { get; set; } 
    ... 
} 

編輯:我很抱歉,我糾正代碼工作!

+0

你chaning在運行時的值?如果是這樣,你應該實現['INPC'](http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged.aspx),它也應該是'public'。 *(順便說一句,「child」的複數是'children')* – 2011-12-18 19:36:43

+0

我是WPF的新手,不確定它是如何工作的。我必須從INotifyPropertyChanged類繼承我的項目,但是如何獲取PropertyChanged處理程序的調用級別高於第一個? – zee 2011-12-18 20:07:40

+0

它不是一個類,它是一個接口,你可能想看看一般的[數據綁定概述](http://msdn.microsoft.com/en-us/library/ms752347.aspx)和[article詳細介紹INPC的實現](http://msdn.microsoft.com/en-us/library/ms229614.aspx)。這與樹級無關。 – 2011-12-18 20:12:24

回答

0

如果你想自動展開所有的孩子們,以及目標項目,那麼你需要向下傳播完成的改變自己,做這樣的事情....

public bool IsExpanded 
{ 
    get { return isExpanded; } 

    set 
    { 
     if (isExpanded != value) 
     { 
      isExpanded = value; 
      if (isExpanded) 
      { 
       foreach(ListItem child in Children) 
        child.IsExpanded = true; 
      } 
      SendPropertyChanged("IsExpanded"); 
     } 
    } 
} 
+0

我想保存整個樹狀態 – zee 2011-12-19 15:10:15

相關問題