2011-07-10 26 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でそれを再現することができました。私は値が66ではなく100であると予想します。答えを見ることを楽しみにしています。 – 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内の値として取得します。あなたの場合には非常に簡単な解決策があります。 Bindingを設定する前に、現在の値を保存することができます。 Bindingが設定されている場合、保存された値をターゲットの高さに再割り当てする必要があります。 –

関連する問題