监控财产的变化

12 c# properties propertychanged

我有2个属性(WPF控件):HorizontalOffsetVerticalOffset(都是公共Double的).每当这些属性发生变化时,我想调用一个方法.我怎样才能做到这一点?我知道一种方法 - 但我很确定这不是正确的方法(使用DispatcherTimer非常短的刻度间隔来监控属性).

编辑更多背景:

这些属性属于telerik scheduleview控件.

And*_*tan 24

利用INotifyPropertyChanged控件的接口实现.

如果调用该控件myScheduleView:

//subscribe to the event (usually added via the designer, in fairness)
myScheduleView.PropertyChanged += new PropertyChangedEventHandler(
  myScheduleView_PropertyChanged);

private void myScheduleView_PropertyChanged(Object sender,
  PropertyChangedEventArgs e)
{
  if(e.PropertyName == "HorizontalOffset" ||
     e.PropertyName == "VerticalOffset")
  {
    //TODO: something
  }
}
Run Code Online (Sandbox Code Playgroud)


Ork*_*zen 6

我知道一种方式...... DispatcherTimer

哇避免那个:) INotifyPropertyChange界面是你的朋友.有关示例,请参阅msdn.

您基本上onPropertyChangedSetter您的属性上触发一个事件(通常称为),并且订阅者处理它.

来自的一个示例实现msdn:

// This is a simple customer class that 
// implements the IPropertyChange interface.
public class DemoCustomer  : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;    
    private void NotifyPropertyChanged(String info)
    {
        if (PropertyChanged != null)
          PropertyChanged(this, new PropertyChangedEventArgs(info));            
    }

    public string CustomerName
    {
        //getter
        set
        {
            if (value != this.customerNameValue)
            {
                this.customerNameValue = value;
                NotifyPropertyChanged("CustomerName");
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)