我对一个类(WPF控件)有两个属性:HorizontalOffset和VerticalOffset (都是公共Double)。每当这些属性发生变化时,我都想调用一个方法。我该怎么做呢?我知道有一种方法--但我非常确定这不是正确的方法(使用非常短的滴答间隔的DispatcherTimer来监控该属性)。
编辑以获取更多上下文:
这些属性属于telerik调度视图控件。
发布于 2012-02-29 23:48:55
利用控件的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-29 23:33:54
我知道有一种方法...
DispatcherTimer
哇,避免这种情况:) INotifyPropertyChange界面是你的朋友。有关示例,请参见the 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");
}
}
}
}https://stackoverflow.com/questions/9501928
复制相似问题