2012-02-29 80 views
8

我有一个类(WPF控件)的2个属性:HorizontalOffsetVerticalOffset(均为公开Double's)。我想在这些属性发生变化时调用方法。我怎样才能做到这一点?我知道一种方式 - 但我很确定这不是正确的方法(使用非常短的滴答间隔的DispatcherTimer来监控该属性)。监视属性变化

编辑更多的上下文:

这些属性属于Telerik的scheduleview控制。

+1

使用事件? http://msdn.microsoft.com/en-us/library/awbftdfh.aspx – 2012-02-29 15:34:11

+0

我知道如何订阅现有的事件 - 但我没有创建自己的事件准备订阅的经验 - 这可能吗?这是你说的最有效率的方式吗? – 2012-02-29 15:36:08

+2

那么,鉴于这些是你不拥有的类型的两个属性;您需要了解Telerik在监控这些属性的控件上是否暴露了什么机制(如果有的话)。鉴于它是WPF,我会认为它是'INotifyPropertyChanged'。在这种情况下,你并没有公开你自己的事件源,你需要希望那个控件上已经存在一个 – 2012-02-29 15:38:08

回答

17

杠杆控制的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 
    } 
} 
+0

完美,正是我在伴侣后 - 谢谢。 – 2012-02-29 15:55:35

5

我知道的一种方式... 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"); 
      } 
     } 
    } 
} 
+0

感谢Zortkun,请参阅我在OP中的编辑(这是一个课程/控制我不能编辑) - 你的答案仍然适用?我现在将研究INotifyPropertyChange。 – 2012-02-29 15:36:35

+1

我对Telerik的东西并不熟悉,Daniel.But在评论中,我看到你问到如何创建事件,我为此发布了一个编辑。 @安德拉斯佐尔坦似乎有你的答案。 :) – 2012-02-29 15:51:45

+0

再次感谢Zortkun – 2012-02-29 15:55:19