私は現時点でWPFとMVVMを学習しています(または少なくとも私は...しようとしています)。Buttonclickのビューを変更する
私は2つのボタンを持つウィンドウを表示する小さなsample-appを作成しました。それぞれには、クリック時の新しいビューが表示されます。そこで私は3つのUserControls(2つのボタンを持つDecisonMakerと、各 "clicktarget"のための1つのUsercontrol)を作成しました。
だから、私はMainWindowViewModelで "CurrentView" と呼ばれるプロパティMainWindow.xamlの
コードにメインウィンドウのCotentControlをバインド:MainWindowViewModelの
<Window x:Class="WpfTestApplication.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfTestApplication"
Title="MainWindow" Height="350" Width="525">
<Window.DataContext>
<local:MainWindowViewModel />
</Window.DataContext>
<Grid>
<ContentControl Content="{Binding CurrentView, Mode=OneWay}" />
</Grid>
</Window>
コード:
class MainWindowViewModel
{
private UserControl _currentView = new DecisionMaker();
public UserControl CurrentView
{
get { return _currentView; }
set { _currentView = value; }
}
public ICommand MausCommand
{
get { return new RelayCommand(LoadMouseView); }
}
public ICommand TouchCommand
{
get { return new RelayCommand(LoadTouchView); }
}
private void LoadMouseView()
{
CurrentView = new UserControlMouse();
}
private void LoadTouchView()
{
CurrentView = new UserControlTouch();
}
}
最初のUserControl(DecisionMaker)が想定どおりに表示されます。また、メソッドLoadMouseView
が呼び出されます。しかし、ビューは変更されません。私は何が欠けていますか?
更新日:ありがとうございます!私はINotifyPropertyChangedインターフェイスを見逃しました。すべてのあなたの答えは素晴らしく、非常に正確で有用でした!私はどちらを受け入れるか分からない - "最初の"答えを受け入れることが最も公正な方法だと思いますか?
私は問題を解決し、MVVMをよりよく理解するのを助けてくれたので、盲目的な答えを受け入れました。しかし、すべての答えは皆さんのおかげで本当に素晴らしかったです!
ビューモデルビュー/ユーザーコントロールへの参照を持つべきではありません。あなたのビューモデルからこれを削除する必要があります。これは良い出発点です:http://msdn.microsoft.com/en-us/magazine/dd419663.aspx – blindmeis