1

每次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");
}

我究竟做错了什么?

4

1 回答 1

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();
}
于 2013-05-24T17:04:12.380 回答