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

前端之家收集整理的这篇文章主要介绍了c# – 不能将附加属性绑定到另一个依赖属性前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我写一个控制库在这个库中有一些用户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),那么我可以

原文链接:https://www.f2er.com/csharp/91945.html

猜你在找的C#相关文章