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

10

我正在编写一个控件库。在这个库中,有一些自定义面板,这些面板中填充了用户的UI元素。由于我的库中的每个子元素都必须有一个“标题”属性,因此我编写了以下代码:

// 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>

如果将“Name”绑定到MyLibCommonProperties中定义的其他附加属性,则绑定似乎可以正常工作。但是,如果尝试将“Binding”设置到“Label”的“SetTitle”属性上,则会抛出异常:“无法在类型为'Label'的'SetTitle'属性上设置'Binding'。只能在DependencyObject的DependencyProperty上设置'Binding'。”

请问我遗漏了什么?提前感谢。


嗨,MyLibCommonProperties必须从DependecyObject派生。 - user572559
1
仅仅是猜测,但是您应该将Get/SetTitle的第一个参数改为DependencyObject,而非UIElement。另外,在注册您的Attache属性时,第三个参数必须是附加属性的所有者,而不是所需的目标。请将它更改为MyLibCommonProperties。 - dowhilefor
HorizontalShelf是什么?你是否尝试在StackPanel或类似的内置控件中使用它?其他一切看起来都很好。我只能假设HorizontalShelf是一个自定义控件,无法将其子元素识别为逻辑子元素。请参见此处:http://kentb.blogspot.com/2008/10/customizing-logical-children.html - Kent Boogaart
1个回答

16

将依赖属性定义中的UIElement替换为MyLibCommonProperties

public static readonly DependencyProperty TitleProperty =
    DependencyProperty.RegisterAttached( 
        "Title", 
        typeof(String),
        typeof(MyLibCommonProperties), // Change this line
        new FrameworkPropertyMetadata(
            "NoTitle", new PropertyChangedCallback(OnTitleChanged))
        );
我认为可能是因为绑定隐式地使用了指定调用SetTitle()的父类,所以它调用的是Label.SetTitle()而不是MyLibCommonProperties.SetTitle()
我在一些自定义TextBox属性中遇到了同样的问题。如果我使用typeof(TextBox),那么我就无法绑定到该值,但是如果我使用typeof(TextBoxHelpers),那么我就可以。

Rachel,这不是你第一次帮助我了!(我相信这也不会是最后一次)。即使过去了将近十年。 - StayOnTarget
哦,哇,我简直不敢相信已经过去了将近十年!现在我感觉自己老了,哈哈。不过我很高兴我的回答仍然有用! :) - Rachel

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接