【问题标题】:WP7: Binding to attached propertiesWP7:绑定到附加属性
【发布时间】: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


【解决方案1】:

将SetMyProperty中第二个参数的类型改为Object类型。

您将获得一个绑定对象,而不是字符串,作为那里的值。

【讨论】:

  • 感谢您的回复。刚试了一下,还是不行。
  • 这是错误的。你永远不会得到一个 Binding 对象,他的 dp 是字符串类型,所以 SetMyPropert 也应该期望一个字符串。 WPF/silverlight 将跟踪评估绑定的方式和时间,以获得 dp 或 ap 的有效值。
【解决方案2】:

并且绑定永远不会触发您的 SetMyProperty - 如果您需要控制值何时更改,则必须使用 PropertyMetadata 的覆盖,它需要一个“更改”处理程序



... new PropertyMetadata(
    null,
    new PropertyChangedCallback((sender, e) => {
      var myThis = (MyClass)sender;
      var changedString = (string)e.NewValue;
      // To whatever you like with myThis ( = the sender object) and changedString (= new value)
    })

【讨论】:

    猜你喜欢
    • 2011-02-07
    • 2011-02-14
    • 1970-01-01
    • 2011-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-02
    相关资源
    最近更新 更多