在DependencyProperty的setter上的C#触发器方法

时间:2013-05-24 17:01:07

标签: c# dependency-properties

我试图在每次更改属性Minutes时触发一个方法,但它永远不会发生。我没有通过XAML设置该属性,而是通过出价来设置。

public static DependencyProperty MinutesProperty =
    DependencyProperty.Register("Minutes", typeof(string), typeof(TimelineControl));

public string Minutes
{
    get { return (string)GetValue(MinutesProperty); }
    set { 
        SetValue(MinutesProperty, value);
        my_method();
    }
}

public void my_method()
{
    Console.WriteLine("foo bar");
}

我做错了什么?

1 个答案:

答案 0 :(得分:3)

如果您通过XAML设置属性,则不会调用您的setter。要正确处理属性更改,您应该在注册时添加对属性元数据的回调:

public static DependencyProperty MinutesProperty =
    DependencyProperty.Register("Minutes", typeof(string), typeof(TimelineControl),
    new PropertyMetadata(OnMinutesChanged));

private static void OnMinutesChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
    // Handle change here

    // For example, to call the my_method() method on the object:
    TimelineControl tc = (TimelineControl)d;
    tc.my_method();
}