pulp
pulp

Reputation: 708

WPF Data Binding: BindingOperations.SetBinding() do not use the value of the Dependency Property

I have a own dependency property Target.Height bound to a normal property Source.Height using BindingOperations.SetBinding(). Updating the Target.Height property should update the Source.Height property. But not the actual value of the dependency property is used rather the default value of the dependency property. Is this the intended behavior?

Thanks for any hints. Code I use:

public class Source
{
  private int m_height;
  public int Height
  {
    get { return m_height; }
    set { m_height = value; }
  }
}

public class Target : DependencyObject
{
  public static readonly DependencyProperty HeightProperty;

  static Target()
  {
    Target.HeightProperty =
      DependencyProperty.Register("Height", typeof(int), typeof(Target),
      new PropertyMetadata(666)); //the default value
  }

  public int Height
  {
    get { return (int)GetValue(Target.HeightProperty); }
    set { SetValue(Target.HeightProperty, value); }
  }
}



Source source = new Source();
Target target = new Target();

target.Height = 100;

Binding heightBinding = new Binding("Height");
heightBinding.Source = source;
heightBinding.Mode = BindingMode.OneWayToSource;

BindingOperations.SetBinding(target, Target.HeightProperty, heightBinding);

//target.Height and source.Height is now 666 instead of 100 ....

Upvotes: 2

Views: 5583

Answers (1)

Marat Khasanov
Marat Khasanov

Reputation: 3848

WPF puts Binding as values of dependency properties. When you setting up a binding you actually replaces your current property value with a new one. At the end of the DependencyObject.SetValueCommon you may find a code that did it. There we can see that WPF gets a default value, then set it as a current property value with expression marker, and then attach BindingExpression which updates the source using the current property value - the default value.

this.SetEffectiveValue(entryIndex, dp, dp.GlobalIndex, metadata, expression, BaseValueSourceInternal.Local);
object defaultValue = metadata.GetDefaultValue(this, dp);
entryIndex = this.CheckEntryIndex(entryIndex, dp.GlobalIndex);
this.SetExpressionValue(entryIndex, defaultValue, expression);
DependencyObject.UpdateSourceDependentLists(this, dp, array, expression, true);
expression.MarkAttached();
expression.OnAttach(this, dp);
entryIndex = this.CheckEntryIndex(entryIndex, dp.GlobalIndex);
effectiveValueEntry = this.EvaluateExpression(entryIndex, dp, expression, metadata, valueEntry, this._effectiveValues[entryIndex.Index)]);
entryIndex = this.CheckEntryIndex(entryIndex, dp.GlobalIndex);

Upvotes: 2

Related Questions