2011-11-10 7 views
2

私はWPVMでMVVMを使用しているプロジェクトに取り組んでおり、難しい状況です。MVVMを使用してContentControl WPFのコンテンツを変更しますか?

ボタンがContentControlの内容を変更するウィンドウにButtonContentControlを作成すると、正常に動作します。

<Window.Resources> 
    <me:UserControl1ViewModel x:Key="viewModel" /> 
</Window.Resources> 

<Grid> 
    <Button Content="Button" 
      Name="button1" 
      Command="{Binding Source={StaticResource viewModel}, Path=ClickCommand}" /> 
    <ContentControl Content="{Binding Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, Source={StaticResource viewModel}, Path=View, ValidatesOnExceptions=True, NotifyOnValidationError=True, ValidatesOnDataErrors=True}" /> 
</Grid> 

しかし、私はボタンでユーザーコントロールを作成し、ボタンが作動しないContentControlに内容を変更したとき。 なぜですか?

<Window.Resources> 
    <me:UserControl1ViewModel x:Key="viewModel" /> 
</Window.Resources> 

<Grid> 
    <v:UserControl1 /> 
    <ContentControl Content="{Binding Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, Source={StaticResource viewModel}, Path=View, ValidatesOnExceptions=True, NotifyOnValidationError=True, ValidatesOnDataErrors=True}" /> 
</Grid> 

ContentControlに

<UserControl.Resources> 
    <me:UserControl1ViewModel x:Key="viewModelA" /> 
</UserControl.Resources> 

<Grid> 
    <Button Content="Button" 
      Name="button1" 
      Command="{Binding Source={StaticResource viewModelA}, Path=ClickCommand}" /> 
</Grid> 

の内容の変更に感謝を呼び出しているユーザーコントロール!

+0

あなたは適切にINotifyPropertyChangedの実装をViewModelにしていますか? – Ekk

答えて

2

2番目の例では、2つの異なるビューモデルにバインドされています。

<Window.Resources> 
    <!-- View Model Instance #0 --> 
    <me:UserControl1ViewModel x:Key="viewModel" /> 
</Window.Resources> 

<UserControl.Resources> 
    <!-- View Model Instance #1 --> 
    <me:UserControl1ViewModel x:Key="viewModelA" /> 
</UserControl.Resources> 

基本的に、UserControlとWindowは同じビューモデルインスタンスを共有していないため、更新は伝播されません。あなたはあなたのユーザーコントロールに同じインスタンスを取得する必要があります。

方法について:

<!-- Window --> 
<v:UserControl1 DataContext="{Binding Source={StaticResource viewModel}}" /> 

<!-- UserControl1 --> 
<Button Content="Button" 
     Name="button1" 
     Command="{Binding Path=ClickCommand}" /> 
関連する問題