Attach an event to a property when changed

ぐ巨炮叔叔 提交于 2019-12-24 02:24:19

问题


Is there any feature of c# (silverlight) in which I can watch a property of a usercontrol for when there is any changes made without using dependency properties? I want one that is not static.


回答1:


There are two standard mechanisms where the "observation" pattern (which is what are describing) is implement. One is the use of dependency properties.

The other is the implementation of the INotifyPropertyChanged interface.

public partial class MyUserControl : UserControl, INotifyPropertyChanged
{

  string _myProperty;
  public string MyProperty
  {
     get { return _myProperty; }
     set
     {
       _myProperty = value;
       NotifyPropertyChanged("MyProperty");
     }
  }

  private void NotifyPropertyChanged(string name)
  {
      if (PropertyChanged != null)
        PropertyChanged(this, new PropertyChangedEventArgs(name);
  }

  public event PropertyChangedEventHandler PropertyChanged
}

In order to watch a property you need to attach to the PropertyChanged event.

MyUserControl control = new MyUserControl();
control += Control_PropertyChanged;

...

void Control_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
    if (e.PropertyName == "MyProperty")
    {
      //Take appropriate action when MyProperty has changed.
    }
}


来源:https://stackoverflow.com/questions/2306746/attach-an-event-to-a-property-when-changed

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!