2010-07-16 57 views
0

試圖爲WPF DependencyObject創建我自己的自定義AttachedProperty未能真正做到我希望它做的事情,而且我有點擔心我(再次)完全不理解WPF概念。AttachedProperty不傳播給孩子?

我做了一個非常簡單的測試課程,以顯示我的問題在哪裏。從the MSDN Documentation,我複製

public class TestBox : TextBox 
{ 
    public static readonly DependencyProperty IsBubbleSourceProperty = DependencyProperty.RegisterAttached(
      "IsBubbleSource", 
      typeof(Boolean), 
      typeof(TestBox) 
      ); 
    public static void SetIsBubbleSource(UIElement element, Boolean value) 
    { 
     element.SetValue(IsBubbleSourceProperty, value); 
    } 
    public static Boolean GetIsBubbleSource(UIElement element) 
    { 
     return (Boolean)element.GetValue(IsBubbleSourceProperty); 
    } 
    public Boolean IsBubbleSource 
    { 
     get 
     { 
      return (Boolean)GetValue(IsBubbleSourceProperty); 
     } 
     set 
     { 
      SetValue(IsBubbleSourceProperty, value); 
     } 
    } 
} 

現在,把我的新時髦的文本框爲一個網格這樣

<Grid vbs:TestBox.IsBubbleSource="true"> 
    <vbs:TestBox x:Name="Test" Text="Test" >      
    </vbs:TestBox> 
</Grid> 

我希望每一個不設置IsBubbleSource屬性本身來自於「繼承」它的孩子其母公司網格。它不這樣做;一個MessageBox.Show(Test.IsBubbleSource.ToString())顯示「錯誤」。附加屬性設置爲true。我使用OnPropertyChanged事件處理程序檢查了這一點。我錯過了什麼?

謝謝!

回答

2

默認情況下,附加屬性不會被繼承。您必須在定義屬性時指定它:

public static readonly DependencyProperty IsBubbleSourceProperty = DependencyProperty.RegisterAttached(
    "IsBubbleSource", 
    typeof(Boolean), 
    typeof(TestBox), 
    new FrameworkPropertyMetadata(false, FrameworkPropertyMetadataOptions.Inherits) 
    ); 
+0

是的,就是這樣。謝謝!我想知道如果它們沒有被繼承,它們有什麼用處...... – Jens 2010-07-16 11:51:04