WPF绑定到我自己的属性

时间:2011-03-09 18:09:14

标签: wpf binding

我创建了自己的UserControl,其中有一些属性是根据某些东西计算的,我们称之为Result。现在,我想把这个控件放在Grid上,我有一些商务对象。我想将此对象中的属性绑定到我的属性Result。所以我做了这样的事情:

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

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

2 个答案:

答案 0 :(得分:2)

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

希望这会有所帮助。 (有一个片段用于将依赖属性的shell添加到您的代码中,在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;  
    }

答案 1 :(得分:1)

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

要默认定义属性TwoWay(通常需要),您需要这样的内容:

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