2011-07-10 72 views
2

我有一個自己的依賴屬性Target.Height綁定到一個正常的屬性Source.Height使用BindingOperations.SetBinding()。更新Target.Height屬性應更新Source.Height屬性。但不是使用依賴項屬性的實際值,而是使用依賴項屬性的默認值。這是預期的行爲嗎?WPF數據綁定:BindingOperations.SetBinding()不使用依賴屬性的值

感謝您的任何提示。我使用的代碼:

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

這絕對是一種奇怪的行爲。我能夠在LINQpad中重現它。我預計價值將是100,而不是666.期待看到答案。 – NathanAW

+0

複製粘貼和調試你的源代碼,這兩個屬性後,你的最後一行代碼,是666 ...奇怪... – stukselbax

回答

2

WPF將綁定作爲依賴項屬性的值。當你建立一個綁定時,你實際上會用新的屬性替換你當前的屬性值。在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); 
+0

感謝您的答案,聽起來很複雜;) – pulp

+1

主要目標是瞭解綁定行爲作爲DependencyObject中的一個值。你的情況有非常簡單的解決方案。您可以在設置綁定之前保存當前值。當設置綁定時,您應該將保存的值重新分配到目標的高度。 –