我有一个派生自INotifyPropertyChanged的类来跟踪属性更改。此属性绑定到TreeView,并且需要在TreeViewItems中执行搜索。当“IsExpanded”冒泡到TreeView的根元素时,属性set this.OnPropertyChanged("IsExpanded")
因某种原因this.PropertyChanged == null
被调用。为什么它在这里为null而在更深的TreeView元素上不为null?我能解决这个问题吗?
我的代码cs:
public class TreeViewItemViewModel:INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
if (this.PropertyChanged != null)
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
....................
bool _isExpanded;
public bool IsExpanded
{
get { return _isExpanded; }
set
{
if (value != _isExpanded)
{
_isExpanded = value;
this.OnPropertyChanged("IsExpanded");
}
//Expand all till the root
if (_isExpanded && _parent != null)
_parent._isExpanded = true;
//Lazy load children, if nessesary
if (this.HasDummyChild)
{
this.Children.Remove(DummyChild);
this.LoadChildren();
}
}
}
bool _isSelected;
public bool IsSelected
{
get { return _isSelected; }
set
{
if (value != _isSelected)
{
_isSelected = value;
this.OnPropertyChanged("IsSelected");
}
}
}
.............................
}
我的代码XAML:
<TreeView ItemsSource="{Binding Areas}">
<TreeView.ItemContainerStyle>
<Style TargetType="{x:Type TreeViewItem}">
<Setter Property="IsExpanded" Value="{Binding IsExpanded, Mode=TwoWay}" />
<Setter Property="IsSelected" Value="{Binding IsSelected, Mode=TwoWay}" />
<Setter Property="FontWeight" Value="Normal" />
<Style.Triggers>
<Trigger Property="IsSelected" Value="True">
<Setter Property="FontWeight" Value="Bold" />
</Trigger>
</Style.Triggers>
</Style>
</TreeView.ItemContainerStyle>
<TreeView.Resources>
<HierarchicalDataTemplate
DataType="{x:Type vAreas:AreaViewModel}"
ItemsSource="{Binding Children}"
>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Name}" />
</StackPanel>
</HierarchicalDataTemplate>
</TreeView.Resources>
</TreeView>
答案 0 :(得分:0)
问题是我从未订阅我的事件PropertyChanged。 一旦我订阅它就开始正常工作
this.PropertyChanged += AreaViewModel_PropertyChanged;
void AreaViewModel_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
if (e.PropertyName == "IsExpanded")
{
//Expand all till the root
if (this.IsExpanded && this.Parent != null)
this.Parent.IsExpanded = true;
//Lazy load children, if nessesary
if (this.HasDummyChild)
{
this.Children.Remove(DummyChild);
this.LoadChildren();
}
}
}
答案 1 :(得分:0)
我挣扎了一段时间。最后,我发现我的收集树视图的集合是一个ObservableCollection属性,但实际上是一个列表。
一旦我把它变成一个ObservableCollection,一切都开始工作了。