开发者

wpf , binding and datacontext

This is my ViewModel -

 public class ViewModel 
{
    public ObservableCollection<Person> Persons { get; set; }
}

and this is Class Person:

public class Person : INotifyPropertyChanged
{
    private string _firstName;
    public string FirstName
    {
        get { return _firstName; }
        set
        {
            _firstName = value;
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs("FirstName"));
            }
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
}

Now,开发者_如何学Go every time one of the persons's FirstName is changing I want to do some tasks, lets say raise a messagebox.

How do I do that ?


You need to implement 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));
     }
}


Typically your person class will use the interface INotifyPropertyChanged, firing the PropertyChanged event whenever FirstName changes. This allows you to bind items in a view to your Person class and the view will be updated when the data changes.

To pop up a message box when any FirstName however, you will need some code behind in your view. One way to do it is to, as before, use INotifyProperty changed and subscribe to that on all Person objects in your view, using MessageBox.Show whenever an event changing FirstName is invoked. You can use the CollectionChanged event in the ObservableCollection to track Person objects in and out of the list to make sure that they are all connected to your Person FirstName changed event handler.

The best way to do it, in my opinion, is to have an event in the ViewModel rather than the Person class which fires whenever a change is made to any Person class (with the specific Person object as an argument). This will only work if the ViewModel is the only thing which can change Person.FirstName, and your View will have to bind to the ViewModel in an appropriate way to effect this.


You need to implement INotifyPropertyChanged on your viewmodel, and raise the property changed event when setting your persons collection. This will allow you listen for the fact that it has changed.

http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged.aspx

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜