2011-09-23 5 views
60

私はコード内にバインディングを設定する必要があります。コードにバインディングを設定する方法は?

私はそれを正しく理解できないようです。

これは私がしようとしたものです:

XAML:背後

<TextBox Name="txtText"></TextBox> 

コード:

Binding myBinding = new Binding("SomeString"); 
myBinding.Source = ViewModel.SomeString; 
myBinding.Mode = BindingMode.TwoWay; 
myBinding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged; 
BindingOperations.SetBinding(txtText, TextBox.TextProperty, myBinding); 

のViewModel:

public string SomeString 
    { 
     get 
     { 
      return someString; 
     } 
     set 
     { 
      someString= value; 
      OnPropertyChanged("SomeString"); 
     } 
    } 

私プロパティが更新されていませんがそれを設定します。

私は間違っていますか?

答えて

127

このお試しください:(あなたは、コンストラクタで行うように)あなたがpathを指定した場合

Binding myBinding = new Binding(); 
myBinding.Source = ViewModel; 
myBinding.Path = new PropertyPath("SomeString"); 
myBinding.Mode = BindingMode.TwoWay; 
myBinding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged; 
BindingOperations.SetBinding(txtText, TextBox.TextProperty, myBinding); 

を、あなたのソースは、.SomeString部分がパスからちょうどViewModelに評価されるべきです。

+7

あなたはまた、単に利益の@ManishDubey :) –

+1

を入力して減らすために、最後の行の代わりにtxtText.SetBinding(TextBox.TextProperty、myBinding)を使用することができます静的メソッドは、最初のパラメーターがDependencyObjectとして定義されているため、FrameworkElementまたはFrameworkContentElement(Freezablesなど)から派生していないオブジェクトのデータバインドを有効にします。 – FreddyFlares

8

オブジェクトをViewModelにするためにソースを変更する必要があります。

myBinding.Source = viewModelObject; 
関連する問題