【问题标题】:why can't show the default value of DependencyProperty为什么无法显示 DependencyProperty 的默认值
【发布时间】:2022-07-22 17:36:42
【问题描述】:

我希望文本块显示附加依赖属性的默认值,但它不起作用。

在xml中

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

依赖属性

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

【问题讨论】:

  • 所以您想在整个应用程序中自动将 MyDependencyObject 附加到 all TextBlocks?这不是它的工作原理。
  • 真的吗?帐号 3 有同样的问题?你为什么要这样做?
  • @KlausGütter 它确实是这样工作的,至少当你明确地请求一个值时。

标签: c# .net wpf xaml


【解决方案1】:

与附加属性的数据绑定需要括号中的路径:

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

附加的属性声明必须使用声明类作为“所有者类型”:

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);
    }
}

【讨论】:

    猜你喜欢
    • 2016-03-18
    • 2016-07-29
    • 2017-11-28
    • 2016-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-31
    相关资源
    最近更新 更多