2011-11-11 86 views
9

我正在寫一個控件庫。在這個庫中有一些用戶UIElements填充的自定義面板。因爲在我的lib每個子元素必須有一個「標題」屬性,我寫了下面:無法將附加屬性綁定到其他依賴項屬性

// Attached properties common to every UIElement 
public static class MyLibCommonProperties 
{ 
    public static readonly DependencyProperty TitleProperty = 
     DependencyProperty.RegisterAttached( 
      "Title", 
      typeof(String), 
      typeof(UIElement), 
      new FrameworkPropertyMetadata(
       "NoTitle", new PropertyChangedCallback(OnTitleChanged)) 
      ); 

    public static string GetTitle(UIElement _target) 
    { 
     return (string)_target.GetValue(TitleProperty); 
    } 

    public static void SetTitle(UIElement _target, string _value) 
    { 
     _target.SetValue(TitleProperty, _value); 
    } 

    private static void OnTitleChanged(DependencyObject _d, DependencyPropertyChangedEventArgs _e) 
    { 
     ... 
    } 
} 

然後,如果我這樣寫:

<dl:HorizontalShelf> 
    <Label dl:MyLibCommonProperties.Title="CustomTitle">1</Label> 
    <Label>1</Label> 
    <Label>2</Label> 
    <Label>3</Label> 
</dl:HorizontalShelf> 

一切工作正常,獲取指定的屬性值,但如果我試圖將其屬性綁定到其他的UIElement的DependencyProperty是這樣的:

<dl:HorizontalShelf> 
    <Label dl:MyLibCommonProperties.Title="{Binding ElementName=NamedLabel, Path=Name}">1</Label> 
    <Label>1</Label> 
    <Label>2</Label> 
    <Label Name="NamedLabel">3</Label> 
</dl:HorizontalShelf> 

一個異常將會被拋出:「一個‘綁定’不能在‘的setTitle’屬性設置類型'標籤'。 A「綁定」只能DependencyObject的一個DependencyProperty設置。」

我缺少什麼?綁定似乎如果不是綁定到做工精細‘名稱’我綁定到MyLibCommonProperties定義的其它一些附加屬性。

在此先感謝。

+0

嗨,MyLibCommonProperties必須從DependecyObject – 2011-11-11 10:59:36

+1

只是一個猜測得到,但改變你的讀/第一的setTitle參數的DependencyObject,不是的UIElement 。在註冊您的Attache屬性時,第三個參數必須是所附屬性的所有者,而不是所需的目標。將其更改爲MyLibCommonProperties。 – dowhilefor

+0

什麼是'Horizo​​ntalShelf'?你是否在'StackPanel'或類似的內置控件中嘗試過?其他一切似乎都很好。我只能假設'Horizo​​ntalShelf'是一個自定義控件,它不會將其子項識別爲邏輯子項。看到這裏:http://kentb.blogspot.com/2008/10/customizing-logical-children.html –

回答

13

替換您的DependencyProperty定義UIElementMyLibCommonProperties

public static readonly DependencyProperty TitleProperty = 
    DependencyProperty.RegisterAttached( 
     "Title", 
     typeof(String), 
     typeof(MyLibCommonProperties), // Change this line 
     new FrameworkPropertyMetadata(
      "NoTitle", new PropertyChangedCallback(OnTitleChanged)) 
     ); 

我想可能是因爲綁定隱含使用父類規範如果可以致電​​因此它調用Label.SetTitle()而不是MyLibCommonProperties.SetTitle()

我對某些自定義TextBox屬性有同樣的問題。如果我用typeof(TextBox)然後我無法綁定到的價值,但如果我用typeof(TextBoxHelpers)然後我可以

+1

+1太棒了!謝謝 – Trap

+0

也適用於我。謝謝 – IFink