【发布时间】:2020-10-21 07:46:54
【问题描述】:
- 我有一个在不同视图模型之间共享的可观察集合。
public class UserInput1ViewModel: INotifyPropertyChanged
{
public ObservableCollection<ParamClass> ParamColl { get; set; }
public UserInput1ViewModel(<ParamClass> paramColl)
{
this.ParamColl = paramColl;
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged([CallerMemberName] string name = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
private void UpdateCollection()
{
this.ParamList = PerformCalculations();
}
}
public class ParamClass
{
public double Property1 { get; set; }
public double Property2 { get; set; }
public double Property3 { get; set; }
... ...
... ...
public double Property19 { get; set; }
}
-
函数
PerformCalculations()将执行,但它不会更新可观察集合中的所有属性。我了解到您无法使用可观察集合 https://stackoverflow.com/a/9984424/4387406 来做到这一点。 -
所以,这就是我目前正在做的事情。
private void UpdateCollection()
{
var output = PerformCalculations();
for(int i = 0; i < output.Count(); i++)
{
this.ParamColl[i].Property1 = output[i].Property1;
this.ParamColl[i].Property2 = output[i].Property2;
... ...
... ...
this.ParamColl[i].Property19 = output[i].Property19;
}
}
- 我的问题是:有没有更好的方法来共享 observable 集合?
非常感谢。
【问题讨论】:
-
为了使
ParamColl[i].Property1 = output[i].Property1;更新 UI,ParamClass 必须实现 INotifyPropertyChanged 接口。如果 PerformCalculations 返回一个 ParamClass 的集合,你当然可以写ParamColl[i] = output[i]; -
谢谢 Clemens,我认为 INotifyPropertyChanged 接口仅适用于视图模型。这对我来说是很棒的学习!谢谢!
标签: c# wpf collections viewmodel