我有一个类(WPF控件)有2个属性:HorizontalOffset和VerticalOffset(都是公共的Double)。我想在这些属性改变时调用一个方法,该怎么做呢?我知道一种方法-但我几乎确定它不是正确的方法(使用一个非常短的tick间隔的DispatcherTimer来监视属性)。
补充更多背景资料:
这些属性属于Telerik ScheduleView控件。
补充更多背景资料:
这些属性属于Telerik ScheduleView控件。
利用控件实现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
}
}
DispatcherTimer
哇,避免使用这个 :) INotifyPropertyChange
接口是您的好朋友。请参阅msdn中的示例。Setter
上触发一个事件(通常称为onPropertyChanged
),然后订阅者处理它。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");
}
}
}
}
INotifyPropertyChanged
。在这种情况下,您没有公开自己的事件源,您需要希望该控件上已经存在一个事件源。 - Andras Zoltan