加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 不能将附加属性绑定到另一个依赖属性

发布时间:2020-12-15 04:21:46 所属栏目:百科 来源:网络整理
导读:我写一个控制库在这个库中有一些用户UIElements填充的自定义面板.由于我的lib中的每个子元素都必须有一个“Title”属性,所以我写了以下内容: // Attached properties common to every UIElementpublic static class MyLibCommonProperties{ public static r
我写一个控制库在这个库中有一些用户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 )
    {
       ...
    }
}

那么,如果我写这个:

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

将抛出异常:“A’Binding”不能在“Label”类型的“SetTitle”属性上设置,“绑定”只能在DependencyObject的DependencyProperty上设置.

我失踪了什么绑定似乎工作正常,而不是绑定到“名称”我绑定到MyLibCommonProperties中定义的一些其他附加属性.

提前致谢.

解决方法

将DependencyProperty定义中的UIElement替换为MyLibCommonProperties
public static readonly DependencyProperty TitleProperty =
    DependencyProperty.RegisterAttached( 
        "Title",typeof(MyLibCommonProperties),// Change this line
        new FrameworkPropertyMetadata(
            "NoTitle",new PropertyChangedCallback(OnTitleChanged))
        );

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读