2013-02-06 17 views
0

我試過這個只是爲了看看會發生什麼,它確實工作,但我不知道爲什麼如此。有人可以解釋我在DependencyProperties的背景中發生了什麼?DependencyProperty奇怪的行爲

我有一個聲明,但DependencyProperty然後在另一個I類靶向DependencyProperty使用GetValueSetValue類。

下面是一個例子:

public class DependencyProperties : DependencyObject 
{ 
    public Size EstimatedSize 
    { 
     get { return (Size)GetValue(EstimatedSizeProperty); } 
     set { SetValue(EstimatedSizeProperty, value); } 
    } 

    public static readonly DependencyProperty EstimatedSizeProperty = 
     DependencyProperty.Register("EstimatedSize", typeof(Size), typeof(DependencyProperties), null); 
} 

public class MyControl: ContentControl 
{ 
    public Size CalculatedSize 
    { 
     get { return (Size)GetValue(DependencyProperties.EstimatedSizeProperty); } 
     set { SetValue(DependencyProperties.EstimatedSizeProperty, value); } 
    } 

    protected override OnApplyTemplate() 
    { 
     // This works but why? How is it possible to do this? What is happening under the hood? 
     this.CalculatedSize = new Size(123, 123); 
    } 
} 

爲什麼能夠做到這一點?這個例子的背景中發生了什麼? MyControl類沒有註冊DP,但可以使用它。有人能告訴我發動機罩下發生了什麼嗎?

+0

可能重複:http://stackoverflow.com/questions/6843877/difference-between-attached-and-non-attached-dependency-properties-in-silverligh – Blachshma

回答

0

我搜索了一下我想給你看的圖片。 請參閱下面的鏈接,DP的概念已有詳細記錄。

http://www.abhisheksur.com/2011/07/internals-of-dependency-property-in-wpf.html

而且,讓我們直接去了底線,當你邀請,並在您的應用程序中使用MyControl,包含DP會自動註冊。 這就是爲什麼DP使用靜態前綴。由於在DP聲明中static readonly的原因,請仔細閱讀https://stackoverflow.com/a/5610015/361100鏈接(Priyank引用的答案)。

+0

如果我使用.Register(... rameworkPropertyMetadataOptions.Inherits)?它不是AttachedProperty,而是嘗試繼承。 – cyberist