Silverlight.绑定到数据对象的附加属性时,没有输入getter



我试图使用附加属性向我的数据对象添加一些表示逻辑。我即将切换到包装器,但我很好奇为什么以下不适合我。表示逻辑类代码为:

    public static readonly DependencyProperty TestPropProperty = DependencyProperty.RegisterAttached(
       "TestProp",
       typeof(string),
       typeof(DataClassPresenter),
       new PropertyMetadata("[Test]")
       );
    public static string GetTestProp(DataClass el)
    {
        return "Haha"; // (string)el.GetValue(TestPropProperty);
    }
    public static void SetTestProp(DataClass el, string val)
    {
        el.SetValue(TestPropProperty, val);
    }
我绑定到属性值的XAML是:
     <TextBlock Text="{Binding Path=(prz:DataClassPresenter.TestProp), StringFormat='Depend:{0}'}"/>

它工作,但总是显示"[Test]","Haha"永远不会返回,GetTestProp永远不会输入。我做错了什么?

这是因为您的get方法不能保证被调用。Silverlight(和WPF)可以单独使用DependencyProperty获取或设置属性值。你不应该在get或set方法中引入任何逻辑。

同样,您不应该使用DataClass作为参数。传递的对象将是您设置附加属性的元素,在您的示例中是一个TextBlock。因此,您应该让上面接受DependencyObjectUIElement而不是DataClass

最新更新