2011-11-11 90 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