wpf、绑定和数据上下文
这是我的ViewModel-wpf、绑定和数据上下文,wpf,binding,datacontext,Wpf,Binding,Datacontext,这是我的ViewModel- public class ViewModel { public ObservableCollection<Person> Persons { get; set; } } 现在,每当一个人的名字改变时,我想做一些事情, 让我们来举一个messagebox 如何做到这一点?您需要在viewmodel上实现INotifyPropertyChanged,并在设置persons集合时引发property changed事件。这将允许你倾听它已经改变的
public class ViewModel
{
public ObservableCollection<Person> Persons { get; set; }
}
现在,每当一个人的名字改变时,我想做一些事情,
让我们来举一个messagebox
如何做到这一点?您需要在viewmodel上实现INotifyPropertyChanged,并在设置persons集合时引发property changed事件。这将允许你倾听它已经改变的事实
您需要实现
INotifyPropertyChanged
public class Person : INotifyPropertyChanged
{
private string firstName;
public string FirstName
{
get { return this.firstName;}
set
{
this.firstName = value;
this.RaisePropertyChanged("FirstName");
MessageBox.Show("Hello World");
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void RaisePropertyChanged(string propertyName)
{
PropertyChangedEventHandler propertyChanged = this.PropertyChanged;
if ((propertyChanged != null))
{
propertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
通常,person类将使用接口INotifyPropertyChanged,在名字更改时触发PropertyChanged事件。这允许您将视图中的项目绑定到Person类,并且当数据更改时,视图将更新 然而,要在任何名字出现时弹出消息框,您需要在视图中隐藏一些代码。一种方法是,像以前一样,在视图中的所有Person对象上使用INotifyProperty changed并订阅它,只要调用了更改名字的事件,就使用MessageBox.Show。您可以在ObservaleCollection中使用CollectionChanged事件来跟踪列表内外的Person对象,以确保它们都连接到Person FirstName changed事件处理程序
在我看来,最好的方法是在ViewModel中有一个事件,而不是Person类,每当对任何Person类进行更改时(使用特定的Person对象作为参数),Person类都会触发该事件。只有当ViewModel是唯一可以更改Person.FirstName的对象时,这才有效,并且您的视图必须以适当的方式绑定到ViewModel才能实现此目的。显示MessageBox的方式与绑定/DataContext或INotifyPropertyChanged无关;我猜OP所寻找的不仅仅是property@Aaron-哦,真的,亚伦,我不明白你怎么解释,“现在,每当一个人的名字改变时,我想做一些任务,比如说提出一个消息框。我怎么做?”,任何其他方式。如果你有一些大的想法,为什么不发布一个答案而不是你的意见。如果问题不清楚,那么向OP询问更多信息。我只是简单地指出了这一点,也许你可以提供一个额外的途径来考虑这些因素。@Aaron,我从来没有说过我不确定他们问题的意义。是你在质疑它。问题很清楚,我的答案也很清楚。谢谢你告诉我如何解释问题和答案,但我想我已经控制住了。问题并不完全清楚,你的答案对你的解释部分正确,但它忽略了一点,即用户的列表可能会发生变化(因为它是可观察的)因此,让此人实现INotifyPropertyChanged只能解决一半的问题(仍然需要在每个对象上订阅事件)
public class Person : INotifyPropertyChanged
{
private string firstName;
public string FirstName
{
get { return this.firstName;}
set
{
this.firstName = value;
this.RaisePropertyChanged("FirstName");
MessageBox.Show("Hello World");
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void RaisePropertyChanged(string propertyName)
{
PropertyChangedEventHandler propertyChanged = this.PropertyChanged;
if ((propertyChanged != null))
{
propertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}