【发布时间】:2016-11-18 07:18:30
【问题描述】:
我在 wpf +mvvm 中有一个场景,即如果我的特定属性在 viewmodel1 中发生变化,那么我想通知 viewmodel2 具有可观察的集合,属性“A”已被更改 1)我想为特定财产而不是全部解雇它。
我尝试了下面的代码但没有工作。请让我知道我是如何做到这一点的。
public class Model1 : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
// Create custom event
public event EventHandler NotifyChange;
private string testProperty;
public string TestProperty
{
get
{
return testProperty;
}
set
{
testProperty = value;
// If changing properties, fire your OnPropertyChanged to update UI
OnPropertyChanged("TestProperty");
}
}
private void OnPropertyChanged(string propName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propName));
// Fire your custom event if a property changed
NotifyChange(this, null);
}
}
}
public class Model2 : INotifyCollectionChanged
{
public event NotifyCollectionChangedEventHandler CollectionChanged;
public Model2()
{
// Assuming there is an accessible instance of model1
Model1 m1Instance = new Model1();
// Hook up your NotifyChange event from model1
m1Instance.NotifyChange += Model1Changed;
}
private void Model1Changed(object sender, EventArgs e)
{
// this will be triggered on change in model1
}
private void OnCollectionChanged(object singleObject)
{
if (CollectionChanged != null)
CollectionChanged(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset, singleObject));
}
}
【问题讨论】:
-
那么,您是说当您在 Model1 上设置属性 TestProperty 时,不会调用 Model2 中的事件处理程序?
-
@TimothyGhanem 我到底想做的是,当我在 viwmodel1 中的属性发生变化时,我想在 viewmodel2 中重新绑定我的可观察集合.....
-
为什么不让Model2继承自ObservableCollection,然后从Model1绑定到UI呢?
-
@stylishCoder :确保两个 VM 都实现 INotifyPropertyChanged。订阅其他视图模型实例的 PropertyChanged 事件。这就是您识别属性更改所需要做的一切。
-
我可以建议您研究一下 PubSub 事件的某种事件聚合器吗?如果您要遵循正确的 MVVM 实践,这将是您的最佳选择。如果可以的话,我建议使用 Prism。以下是更多信息:c-sharpcorner.com/UploadFile/5ffb84/…
标签: c# wpf silverlight mvvm