【问题标题】:WPF Binding to my own propertyWPF 绑定到我自己的财产
【发布时间】:2011-03-09 18:09:13
【问题描述】:

我创建了我自己的 UserControl,它有一些从某些东西计算出来的属性,我们称之为 Result。现在,我想将此控件放在 Grid 上,并且我有一些业务对象。我想将此对象中的属性绑定到我的属性 Result。所以我做了这样的事情:

<MyControl Result="{Binding PropertyInObject}" ...

当然 DataContext 已设置并且其他属性(wpf 属性)的绑定正在工作。但这个不是。 首先它发出一个异常,说我不能绑定到非依赖属性。所以我把它注册为一个。现在它没有给出异常但也没有完成工作。那我该怎么办?

【问题讨论】:

  • 在调试器中运行您的应用程序并查看 VS 输出窗口。在那里打印绑定错误消息。
  • 你能展示你的控件的代码和实例化它的 XAML 吗?
  • WPF Binding to my own property 的可能重复项
  • 您在不到一个小时前刚刚发布了这个确切的问题。请阅读FAQ,欢迎来到 SO。

标签: wpf binding


【解决方案1】:

在没有看到您的代码和问题描述的情况下,听起来您的“结果”属性位于用户控件的代码隐藏中。如果这是真的,那么您需要创建“结果”作为依赖属性。然后您可以在另一种方法中设置您的 Result 值(例如使用 SetResult())

希望这会有所帮助。 (有一个 sn-p 用于将依赖属性的外壳放入代码中,在 VS 2010 中,键入“propdp”,然后按两次 TAB。)

    public int Result
    {
        get { return (int)GetValue(ResultProperty); }
        set { SetValue(ResultProperty, value); }
    }

    // Using a DependencyProperty as the backing store for Result.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty ResultProperty =
        DependencyProperty.Register("Result", typeof(int), typeof(MyClassName), new UIPropertyMetadata(0));

    private void SetResult()
    {
        int resultValue = 0;
        // Do calculations
        Result = 0;  
    }

【讨论】:

    【解决方案2】:

    问题可能是您假设默认绑定是 TwoWay,但事实并非如此。在开发自定义控件时,您确实需要在定义属性时仔细考虑。

    要默认定义一个属性 TwoWay(你通常想要的),你需要这样的东西:

    public static readonly DependencyProperty PropProperty =
            DependencyProperty.Register("Prop", typeof(Boolean), typeof(MyControl), new FrameworkPropertyMetadata(true, FrameworkPropertyMetadataOptions.**BindsTwoWayByDefault**));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-07-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-16
      • 2022-01-23
      • 1970-01-01
      • 2010-12-26
      相关资源
      最近更新 更多