13

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

编辑更多内容:

这些属性属于 Telerik scheduleview 控件。

4

2 回答 2

25

利用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
  }
}
于 2012-02-29T15:48:54.917 回答
6

我知道一种方法...DispatcherTimer

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

您基本上会在您的属性上触发一个事件(通常称为onPropertyChanged),然后订阅者处理它。Setter

一个示例实现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");
            }
        }
    }
}
于 2012-02-29T15:33:53.757 回答