【问题标题】:Can't bind an attached property to another dependency property无法将附加属性绑定到另一个依赖属性
【发布时间】:2011-12-26 22:21:10
【问题描述】:

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

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

将引发异常:“不能在 'Label' 类型的 'SetTitle' 属性上设置 'Binding'。'Binding' 只能在 DependencyObject 的 DependencyProperty 上设置。”

我错过了什么?如果绑定到 MyLibCommonProperties 中定义的其他附加属性,而不是绑定到“名称”,则绑定似乎可以正常工作。

提前致谢。

【问题讨论】:

  • 嗨,MyLibCommonProperties 必须从 DependecyObject 派生
  • 只是猜测,但将您的 Get/SetTitle 第一个参数更改为 DependencyObject,而不是 UIElement。此外,在注册 Attache 属性时,第三个参数必须是附加属性的所有者,而不是所需的目标。将其更改为 MyLibCommonProperties。
  • 什么是HorizontalShelf?您是否在 StackPanel 或类似的内置控件中尝试过?其他一切似乎都很好。我只能假设HorizontalShelf 是一个自定义控件,它不会将其子项识别为逻辑子项。见这里:kentb.blogspot.com/2008/10/customizing-logical-children.html

标签: c# wpf xaml binding attached-properties


【解决方案1】:

将 DependencyProperty 定义中的 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 这不是你的答案第一次帮助我! (我敢肯定它不会是最后一次)。即使在将近十年之后。
  • @UuDdLrLrSs 哇,我不敢相信已经快十年了!现在我觉得老了,哈哈,我很高兴我的答案仍然有用! :)
猜你喜欢
  • 2020-12-22
  • 2012-08-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多