WP7:绑定到附加属性
我正在尝试将数据值绑定到附加属性。然而,它就是无法让它发挥作用。
我将其定义为:
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" />
我缺少什么?
注意:上面的示例是显示相同奇怪行为的最小版本。当然,我的实际实现比这更有意义。
预先感谢您的任何提示!
I'm trying to bind a data value to an attached property. However, it just dont get it to work.
I defined it like:
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);
}
}
Now the XAML I use it looks something like this:
<TextBlock local:MyClass.MyProperty="{Binding MyStringValue}" />
I set a breakpoint in the SetMyProperty method, but it is never called. It does not raise any error, it is just never set or asked for. However, if I change the value in XAML to a fixed string, it gets called:
<TextBlock local:MyClass.MyProperty="foobar" />
What am I missing?
Note: the above example is the minimal version that shows the same strange behavior. My actual implementation makes more sense than this of course.
Thanks in advance for any hint!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
并且绑定永远不会触发您的 SetMyProperty - 如果您需要控制值何时更改,则必须使用 PropertyMetadata 需要一个“Change”-Handler
And the binding wont trigger your SetMyProperty ever - if you need controll over when the value changes you must use the override of PropertyMetadata that expects a "Change"-Handler
将 SetMyProperty 中第二个参数的类型更改为 Object 类型。
您将获得一个 Binding 对象,而不是 String,作为那里的值。
Change the type of the second argument in SetMyProperty to type Object.
You are going to get a Binding object, not a String, as the value there.