【问题标题】:WPF Data Binding: BindingOperations.SetBinding() do not use the value of the Dependency PropertyWPF 数据绑定:BindingOperations.SetBinding() 不使用依赖属性的值
【发布时间】:2011-07-10 20:51:33
【问题描述】:

我有一个自己的依赖属性 Target.Height 使用 BindingOperations.SetBinding() 绑定到普通属性 Source.Height。更新Target.Height 属性应该更新Source.Height 属性。但不是使用依赖属性的实际值,而是使用依赖属性的默认值。这是预期的行为吗?

感谢您的任何提示。我使用的代码:

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 ....

【问题讨论】:

  • 这绝对是一种奇怪的行为。我能够在 LINQpad 中重现它。我希望值是 100,而不是 666。期待看到答案。
  • 复制粘贴和调试你的源代码,这两个属性在你最后一行代码之后,都是666...奇怪...

标签: wpf data-binding c#-3.0 dependency-properties


【解决方案1】:

WPF 将 Binding 作为依赖属性的值。设置绑定时,实际上是用新的属性值替换了当前属性值。在 DependencyObject.SetValueCommon 的末尾,您可能会找到执行此操作的代码。在那里我们可以看到 WPF 获取了一个默认值,然后将其设置为带有表达式标记的当前属性值,然后附加 BindingExpression,它使用当前属性值(默认值)更新源。

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

【讨论】:

  • 主要目标是理解Binding作为DependencyObject内部的一个值。您的情况有一个非常简单的解决方案。您可以在设置 Binding 之前保存当前值。设置绑定后,您应该将保存的值重新分配给目标的高度。
猜你喜欢
  • 1970-01-01
  • 2012-11-08
  • 2010-10-09
  • 2014-08-31
  • 2023-03-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多