XAML 为什么不显示附加属性的默认值?

1mrurvl1  于 2022-12-07  发布在  其他
关注(0)|答案(1)|浏览(133)

我希望TextBlock显示附加属性的默认值,但它不起作用。
XAML语言

<TextBlock Text="{Binding RelativeSource={RelativeSource Self}, Path=MyData}" />

附加属性

public class MyDependencyObject
{
    public static readonly DependencyProperty MyDataProperty =
        DependencyProperty.RegisterAttached("MyData", typeof(string), typeof(TextBlock),
            new FrameworkPropertyMetadata("MyDependencyObject"));

    public static string GetMyData(DependencyObject dpo)
    {
        return (string)dpo.GetValue(MyDataProperty);
    }

    public static void SetMyData(DependencyObject dpo, string value)
    {
        dpo.SetValue(MyDataProperty, value);
    }
}

当我设置MyData的值时,它运行良好。

<TextBlock local:MyDependencyObject.MyData="Test"
           Text="{Binding RelativeSource={RelativeSource Self}, Path=MyData}" />
bbmckpt7

bbmckpt71#

数据系结至附加属性需要括号中的Path,请参阅数据系结中对象的PropertyPath:

<TextBlock Text="{Binding RelativeSource={RelativeSource Self},
                          Path=(local:MyDependencyObject.MyData)}"/>

附加的属性声明必须使用声明类作为RegisterAttached的ownerType参数

public class MyDependencyObject
{
    public static readonly DependencyProperty MyDataProperty =
        DependencyProperty.RegisterAttached(
            "MyData",
            typeof(string),
            typeof(MyDependencyObject), // here
            new FrameworkPropertyMetadata("MyDependencyObject"));

    public static string GetMyData(DependencyObject obj)
    {
        return (string)obj.GetValue(MyDataProperty);
    }

    public static void SetMyData(DependencyObject obj, string value)
    {
        obj.SetValue(MyDataProperty, value);
    }
}

尽管从未在TextBlock上显式设置附加属性,但它将显示“MyDependencyObject”默认值。

相关问题