2011-12-18 97 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

相关问题