Search code examples
c#wpfbindingcode-behind

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


There is a nice control from Thomas Levesque:

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

I'd like to hide Data initialization into constructor, to simply use it like this:

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

Here is my not working attempt (complete code in case link die):

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

What am I doing wrong?


Solution

  • Do not set the Source property of the Binding. You also did not do that in XAML.

    The equivalent of the XAML expression Data="{Binding}" is

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