2016-08-02 23 views
1

は、ここに私のDemoModel.csクラスプロパティをテキストブロック/テキストボックスにバインドする方法は?

public int Age {get; set;} 

DemoViewModel.cs

DemoViewModel() 
{ 
    DemoModel dm = new DemoModel(); 
    dm.Age = 22; 
} 

マイビューで

<TextBlock FontSize="20" Text="{Binding Age,Mode=OneWay}"></TextBlock> 

私は私のTextBlockには何もバインドを取得didntは上記のプログラムを実行します

。 。貴重なご意見をお寄せください。 TIA

+1

DemoViewModelのオブジェクトでビューのDataContextを設定していますか? – CarbineCoder

答えて

0

これを試してください。それは動作するはずです。 INotifyPropertyChangedを実装し、プロパティが変更されたことをビューに通知するためにPropertyChangedイベントを発生させる必要があります。 AgeプロパティをTextBlockにバインドしても問題ありません。

public class DemoViewModel : INotifyPropertyChanged 
{ 
    public event PropertyChangedEventHandler PropertyChanged; 

    private int age; 

    public int Age 
    { 
     get { return age; } 
     set 
     { 
      if (value != age) 
      { 
       age = value; 
       NotifyPropertyChanged("Age"); 
      }  
     } 
    } 

    private void NotifyPropertyChanged(String info) 
    { 
     if (PropertyChanged != null) 
     { 
      PropertyChanged(this, new PropertyChangedEventArgs(info)); 
     } 
    } 
} 

また、あなたの意見DataContextDemoViewModelに設定されていることを確認してください。ビュー

+0

私疲れ上記が、結果は...はい私が設定している同じである 'DataContext'に' DemoViewModel' ... 'パブリックパーシャルクラスDemoView:ユーザーコントロール { プライベートDemoViewModel _viewModel。 public DemoViewModel ViewModel { get {return _viewModel; } セット{_viewModel =値; } } public DemoView() { InitializeComponent(); ViewModel =新しいDemo.ViewModel.DemoViewModel(); this.DataContext = ViewModel; } } ' – surya

+0

あなたのビューモデルクラスがpublic' public class DemoViewModel'であることを確認してください。それは私の最後にうまくいきます。 – ViVi

+0

はい、既にpublicに設定されています。メインウィンドウで何かを変更する必要があります。 'xmlns:local =" clr-namespace:Demo.ViewModel " xmlns:views =" clr-namespace:Demo.View " MC:無視可能= "D" タイトル= "メインウィンドウ" 高さ= "350" 幅= "525"> <ビュー:DemoView /> surya

0

public int Age {get; set;} 

は通常、これはあなたの問題を解決しなければならないモデル

ではViewModelに

public class DemoViewModel : INotifyPropertyChanged 
{ 
public event PropertyChangedEventHandler PropertyChanged; 

private int age; 

public int Age 
{ 
get { return age; } 
set 
{ 
    if (value != age) 
    { 
     age = value; 
     NotifyPropertyChanged("Age"); 
    }  
} 
} 

private void NotifyPropertyChanged(String info) 
{ 
if (PropertyChanged != null) 
{ 
    PropertyChanged(this, new PropertyChangedEventArgs(info)); 
} 
} 
} 

で見る

xmlns:local="clr-namespace:Demo.ViewModel" 
xmlns:views="clr-namespace:Demo.View" 
xmlns:viewModel="clr-namespace:Demo.ViewModel" 
mc:Ignorable="d" Title="MainWindow" 
Height="350" Width="525"> 
<window.DataContext> 
<viewModel:DemoViewModel/> 
</window.DataContext> 
<grid> 
<TextBlock FontSize="20" Text="{Binding Age,Mode=OneWay}"></TextBlock> 
</grid> 

でのDataContextを指定します。使用している場合は、ビューの背後にコードを記述しないようにしてください。私の例ではxaml自体にdatacontextを設定します

関連する問題