How do I use INotifyPropertyChanged in WinRT?

二次信任 提交于 2019-12-04 22:17:52

You need to implement the interface and send out the notification once the given property you care about changes.

        public event PropertyChangedEventHandler PropertyChanged;

        public string CustomerName
        {
            get
            {
                return this.customerNameValue;
            }

            set
            {
                if (value != this.customerNameValue)
                {
                    this.customerNameValue = value;
                    if (PropertyChanged != null)
                    {
                        PropertyChanged(this, new PropertyChangedEventArgs("CustomerName"));
                    }
                }
            }
        }

Keep in mind that for a collection, you should use an ObservableCollection as it will take care of the INotifyCollectionChanged being fired when an item is added or removed.

I would suggest to scale your sample back as far as possible. Don't start with a DataGrid but rather a simple TextBoxand Button, where the Button forces a change in your ViewModel which will then reflect on the UI.

Code taken from here.

It's best to implement a parent class which implements it like this:

public class NotifyPropertyChangedBase : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged = delegate { };

    protected void RaisePropertyChanged(string propertyName)
    {
        PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
}

And then in your subclass (i.e. ViewModel) in your property do something like this:

public class MyViewModel : NotifyPropertyChangedBase
{
    private string _name;
    public string Name {
      get{ return _name; }
      set{ 
       _name = value;
       RaisePropertyChanged("Name");
      }
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!