[英]C# trigger method on setter of a DependencyProperty
我試圖在每次更改屬性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");
}
我究竟做錯了什么?
如果您通過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();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.