简体   繁体   English

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

[英]C# trigger method on setter of a DependencyProperty

I am trying to trigger a method every time the property Minutes is changed, however it never happens. 我试图在每次更改属性Minutes时触发一个方法,但它永远不会发生。 I am not setting the property through XAML , it is being set by a bidding. 我没有通过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");
}

What am I doing wrong? 我究竟做错了什么?

If you are setting the property through XAML, then your setter won't be called. 如果您通过XAML设置属性,则不会调用您的setter。 To properly handle property changes, you should add a callback to the property's metadata when registering: 要正确处理属性更改,您应该在注册时向属性的元数据添加回调:

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();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM