C# 监控财产变化
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9501928/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Monitor a change in property
提问by
I have 2 properties to a class (WPF control): HorizontalOffsetand VerticalOffset(both public Double's). I would like to call a method whenever these properties change. How can I do this? I know of one way - but I'm pretty sure it's not the right way (using a DispatcherTimerof very short tick intervals to monitor the property).
我有一个类的 2 个属性(WPF 控件):HorizontalOffset和VerticalOffset(都是 publicDouble的)。每当这些属性发生变化时,我想调用一个方法。我怎样才能做到这一点?我知道一种方法 - 但我很确定这不是正确的方法(使用DispatcherTimer非常短的滴答间隔来监视属性)。
EDIT FOR MORE CONTEXT:
编辑更多上下文:
These properties belong to a telerik scheduleview control.
这些属性属于 Telerik scheduleview 控件。
采纳答案by Andras Zoltan
Leverage the INotifyPropertyChangedinterface implementation of the control.
利用INotifyPropertyChanged控件的接口实现。
If the control is called myScheduleView:
如果调用控件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
}
}
回答by Orkun Ozen
I know of one way ...
DispatcherTimer
我知道一种方法...
DispatcherTimer
Wow avoid that :) INotifyPropertyChangeinterface is your friend. See the msdnfor samples.
哇,避免那个:)INotifyPropertyChange界面是你的朋友。有关示例,请参阅msdn。
You basically fire an event(usually called onPropertyChanged) on the Setterof your properties and the subscribers handle it.
您基本上会onPropertyChanged在Setter您的属性上触发一个事件(通常称为),并且订阅者会处理它。
an example implementation from the msdngoes:
一个示例实现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");
}
}
}
}

