如何在代码中设置“{Binding}”?

时间:2018-01-24 11:26:18

标签: c# wpf binding code-behind

Thomas Levesque有nice control

<local:BindingProxy x:Key="proxy" Data="{Binding}" />

我想隐藏 Data初始化到构造函数中,只需像这样使用它:

<local:BindingProxy x:Key="proxy" />

这是我的不工作尝试(链接死亡时的完整代码):

public class BindingProxy : Freezable
{
    #region Overrides of Freezable

    protected override Freezable CreateInstanceCore()
    {
        return new BindingProxy();
    }

    #endregion

    public object Data
    {
        get { return (object)GetValue(DataProperty); }
        set { SetValue(DataProperty, value); }
    }

    // Using a DependencyProperty as the backing store for Data.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty DataProperty =
        DependencyProperty.Register("Data", typeof(object), typeof(BindingProxy), new UIPropertyMetadata(null));

    public BindigProxy()
    {
        BindingOperations.SetBinding(this, DataProperty, new Binding { Source = this });
    }
}

我做错了什么?

1 个答案:

答案 0 :(得分:4)

不要设置Binding的Source属性。您也没有在XAML中这样做。

XAML表达式Data="{Binding}"的等价物是

BindingOperations.SetBinding(this, DataProperty, new Binding());