【发布时间】:2011-11-01 09:00:32
【问题描述】:
我正在尝试将数据值绑定到附加属性。但是,它只是无法正常工作。
我是这样定义的:
public static class MyClass
{
public static readonly DependencyProperty MyPropertyProperty =
DependencyProperty.RegisterAttached("MyProperty", typeof(string),
typeof(MyClass), new PropertyMetadata(null));
public static string GetMyProperty(DependencyObject d)
{
return (string)d.GetValue(MyPropertyProperty);
}
public static void SetMyProperty(DependencyObject d, string value)
{
d.SetValue(MyPropertyProperty, value);
}
}
现在我使用的 XAML 看起来像这样:
<TextBlock local:MyClass.MyProperty="{Binding MyStringValue}" />
我在 SetMyProperty 方法中设置了一个断点,但它从未被调用。它不会引发任何错误,只是从不设置或要求。但是,如果我将 XAML 中的值更改为固定字符串,则会调用它:
<TextBlock local:MyClass.MyProperty="foobar" />
我错过了什么?
注意:上面的示例是显示相同奇怪行为的最小版本。当然,我的实际实现比这更有意义。
提前感谢您的任何提示!
【问题讨论】:
-
AFAIR 即使需要获取/设置 WPF/Silverlight 也可能不会直接调用它们。这就是你的断点没有被命中的原因,因为 WPF/Silverlight 正在使用反射(只是一个猜测)或直接使用 SetValue。你说它不起作用,值是否正确但你的断点没有被命中?然后就正常了。抱歉,在 MSDN 中找不到此内容的来源,但我知道我在某处读过它。
-
@dowhilefor:这是有道理的。当我搜索它时,我只是没有找到任何关于它的东西......
-
你的get/set声明有错误,应该是:return (string)d.GetValue(MyPropertyProperty);
-
不,它(silverlight)不使用反射 - 这是 WPF/Silverlight 中属性系统的工作方式 - 数据不在对象中,但在一种静态类绑定中会改变这个值不在你的实例上,实例中的 getter/setter 也在使用这个(GetValue/SetValue)
-
@Philip Daubmeier 最后我发现它在寻找XAML Loading and Dependency Properties
标签: c# data-binding windows-phone-7 dependency-properties