2013-02-06 27 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