无法将附加属性绑定到另一个依赖项属性

Tra*_*rap 9 c# wpf xaml binding attached-properties

我在写一个控制库.在这个库中有一些自定义面板,其中填充了用户UIElements.由于我的lib中的每个子元素都必须具有"Title"属性,因此我写了以下内容:

// 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 )
    {
       ...
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,如果我写这个:

<dl:HorizontalShelf>
    <Label dl:MyLibCommonProperties.Title="CustomTitle">1</Label>
    <Label>1</Label>
    <Label>2</Label>
    <Label>3</Label>
</dl:HorizontalShelf>
Run Code Online (Sandbox Code Playgroud)

一切正常,属性获取指定的值,但如果我尝试将该属性绑定到其他一些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>
Run Code Online (Sandbox Code Playgroud)

抛出一个异常:"'Binding'不能在'Label'类型的'SetTitle'属性上设置.'Binding'只能在DependencyObject的DependencyProperty上设置."

我错过了什么?绑定似乎工作正常,如果不绑定到"名称"我绑定到MyLibCommonProperties中定义的一些其他附加属性.

提前致谢.

Rac*_*hel 13

UIElementDependencyProperty定义替换为MyLibCommonProperties

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

我想这可能是因为绑定隐式使用指定的父类来调用,SetTitle()所以它调用Label.SetTitle()而不是MyLibCommonProperties.SetTitle()

我有一些自定义TextBox属性的问题.如果我使用typeof(TextBox)然后我无法绑定到该值,但如果我使用,typeof(TextBoxHelpers)那么我可以