2013-08-27 48 views
1

我想註冊一個網格控件附加屬性的WPF,但是,我今天遇到非常奇怪的行爲當我這樣寫的時候,附屬屬性的setter永遠不會被執行。並且價值永遠不會被設置。但我可以窺探到網格中,發現附加的屬性附有一個空值。爲WPF附加屬性奇怪的行爲,並結合

但是當我改變附加屬性名:

public static readonly DependencyProperty MyPropertyProperty = 
     DependencyProperty.RegisterAttached("xxxMyProperty", typeof(string), 
     typeof(MyClass), null); 

即使用比其他myProperty的不同的名稱。那麼斷點可以被擊中!和價值可以設置!

而且,當我改變附加屬性爲:

public static readonly DependencyProperty MyPropertyProperty = 
     DependencyProperty.RegisterAttached("MyProperty", typeof(string), 
     typeof(UIElement), null); 

即改變所有者類型的UIElement,那麼我也可以打斷點,只是想知道爲什麼嗎?

然而,當我設置一個,而不是一個字符串常量在XAML綁定,上面會每種情況下有一個例外,說A 'Binding' can only be set on a DependencyProperty of a DependencyObject

綁定XAML例如:

<GridControl local:MyClass.MyProperty="{Binding MyStringValue}"> 
... 
</GridControl> 

有誰遇到過這種奇怪的行爲?我的情況是什麼?在此先感謝您的回覆!

回答

1

如果你指的是SetMyProperty方法作爲'setter',那麼你應該知道這些方法只是'輔助'方法供你使用。框架通常不使用這些方法。

但是,如果您要說的是,您想知道價值何時發生變化,那麼還有另外一種方法。添加一個PropertyChangedCallback處理程序的屬性聲明:

public static readonly DependencyProperty MyPropertyProperty = 
    DependencyProperty.RegisterAttached("MyProperty", typeof(string), typeof(MyClass), 
    new UIPropertyMetadata(default(string.Empty), OnMyPropertyChanged)); 

public static void OnMyPropertyChanged(DependencyObject dependencyObject, 
    DependencyPropertyChangedEventArgs e) 
{ 
    string myPropertyValue = e.NewValue as string; 
} 
+0

謝謝你的答案,這就是我需要的!對於遲到的回覆感到抱歉。 – Ryanch