我正在使用通用列表作为我的财产。我正在致电INotifyPropertyChange
将此属性更新为UI,但除非整个列表已更改,否则它将无法工作。
有效的代码:
public class ClassA : INotifyPropertyChange
{
public event PropertyChangedEventHandler PropertyChanged;
private void OnNotifyPropertyChanged( string p)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(p));
}
public List<ClassB> listA
{
get
{
return new list<ClassB>()
{
new ClassB(property1, property2),
};
}
}
无效的代码:
public class ClassA : INotifyPropertyChange
{
public list<ClassB> listB = new list<ClassB>(new ClassB(property1, property2) );
public event PropertyChangedEventHandler PropertyChanged;
private void OnNotifyPropertyChanged( string p)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(p));
}
public List<ClassB> listA
{
get
{
foreach(item a in ListB)
{ a.property1 = something, a.property2 = something}
return listB;//aparently, items in ListB have changed but UI doesnt update
}
}
}
对于ClassB,我有:
public class ClassB
{
public string Property1 {get;set;}
public string Property2 {get;set;}
}
我将在Update()函数中每秒调用OnNotifyPropertyChanged("ListA")
。
InXAML,
<ListBox Style="{StaticResource ListBoxListAStyle}" Grid.Row="2" ItemsSource="{Binding ListA }" />
如上所述,第一个工作正常,但是当我对ListB
进行更改并将ListB
退还给ListA
时,它将不再更新UI。 PS:我在其他地方打过OnNotifyPropertyChanged(string ListA)
,我认为应该没问题。
编辑:
在第二种情况下,我不确定如何在致电PropertyChanged
时检查我的OnNotifyPropertyChanged(string ListA)
是否被解雇。但它只是不会更新UI。我尝试使用ObservableCollection <T>
而不是List<T>
,但似乎仅将List更改为ObservableCollection不是那么简单吗?我注意到的一件奇怪的事是,在相应XAML的ListBox中,即使程序由于断点而暂停,ListA的ItemsSource也在更改。当我打开/关闭XAML文件时,我看到它正在更改,但是它不会为我更新UI。
更新:
看来,在这种情况下,一旦您为ClassB实现了INotifyPropertyChange
接口,它便开始工作。希望这可以对您有任何帮助。
答案 0 :(得分:1)
对于集合,您需要3种变更通知: