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

How to set "{Binding}" in code behind?

有来自 Thomas Levesque 的 nice control

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

我想隐藏 Data 构造函数中的初始化,以便像这样简单地使用它:

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

这是我的失败尝试(完整代码以防 link 死掉):

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 });
    }
}

我做错了什么?

不设置Binding的Source 属性。您在 XAML.

中也没有这样做

XAML 表达式 Data="{Binding}" 的等效项是

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