有人可以解释为什么我不能使用新来重置绑定数据吗?
使用MVVM,数据绑定到ListBox。
DataList已经实现了INotifyPropertyChanged。
在方法OnChange()
中public void OnChange()
{
data = new ObservableCollection<DataList>(); // not work
data.Add(new DataList() { Text = "Changed 1" });
data.Add(new DataList() { Text = "Changed 2" });
}
但
public void OnChange()
{
data.Clear(); // works fine
data.Add(new DataList() { Text = "Changed 1" });
data.Add(new DataList() { Text = "Changed 2" });
}
ViewModel
ObservableCollection<DataList> data;
public ObservableCollection<DataList> Data
{
get { return data; }
set { data = value; }
}
public ViewModel()
{
this.Command_OnChange = new RelayCommand(ExecuteCommand1, CanExecuteCommand);
data = new ObservableCollection<DataList>();
data.Add(new DataList() { Text = "Default 1" });
data.Add(new DataList() { Text = "Default 2" });
}
public void OnChange()
{
data.Add(new DataList() { Text = "Changed 1" });
data.Add(new DataList() { Text = "Changed 2" });
}
答案 0 :(得分:1)
因为当您更改支持字段时,wpf无法知道更改。
事实上,您可以使用ObservableCollection
的新实例覆盖变量,但您必须在INotifyPropertyChanged
课程中实施ViewModel
。
private ObservableCollection<DataList> data;
public ObservableCollection<DataList> Data
{
get { return data; }
set
{
data = value;
OnPropertyChanged("Data");
}
}
在你的OnChange方法中
public void OnChange()
{
Data = new ObservableCollection<DataList>();//Note the use of Data property not field
Data.Add(new DataList() { Text = "Changed 1" });
Data.Add(new DataList() { Text = "Changed 2" });
}