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

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

概述我写一个控制库在这个库中有一些用户UIElements填充的自定义面板.由于我的lib中的每个子元素都必须有一个“Title”属性,所以我写了以下内容: // Attached properties common to every UIElementpublic static class MyLibCommonProperties{ public static readonly Dep 我写一个控制库在这个库中有一些用户UIElements填充的自定义面板.由于我的lib中的每个子元素都必须有一个“Title”属性,所以我写了以下内容:
// Attached propertIEs common to every UIElementpublic 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),那么我可以

总结

以上是内存溢出为你收集整理的c# – 不能将附加属性绑定到另一个依赖属性全部内容,希望文章能够帮你解决c# – 不能将附加属性绑定到另一个依赖属性所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/1262969.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-06-08
下一篇2022-06-08

发表评论

登录后才能评论

评论列表(0条)

    保存