1つのウィンドウを含むWPFアプリケーションがあります。このウィンドウをスローするだけで、ユーザーはアプリ内でナビゲーションを実行できます。WPF MVVM:MainWindow navigation
アプリケーション構造は以下の通りである:
- MainWindow.xaml
- MainWindowViewModel.cs
- StartPage.xaml
- StartPageViewMode.cs
- Systems.xaml
- Systems.cs
- 別のビューと関連するビューモデル。
MainWindow.xaml
<Grid>
<ContentControl Content="{Binding CurrentWorkspace}" x:Name="ContentControlMainWindow" VerticalAlignment="Stretch"/>
</Grid>
MainWindowViewModel.cs
private ContentControl _currentWorkspace;
public ContentControl CurrentWorkspace
{
get => _currentWorkspace;
set => SetProperty(ref _currentWorkspace, value);
}
//c'tor
public MainWindowViewModel()
{
CurrentWorkspace.Content = new ContentControl { Content = new StartPage()
}
あなたが見ることができるように、アプリケーションの初期化時に、私はCurrentWorkspaceへスタートページビューをロードしています。 StartPageViewModelから、私はCurrentWorkspaceのコンテンツを別のビューに変更する必要があります。 基本的には、このCurrentWorkspaceをアプリケーションの各部分から制御(および変更)するのに苦労しています。
MainWindowViewModel.csで:MainWindow.xamlで
// You would more likely type this as something like ViewModelBase/ObservableObject/etc.
private object _currentWorkspace;
public object CurrentWorkspace
{
get => _currentWorkspace;
set => SetProperty(ref _currentWorkspace, value);
}
private StartPageViewModel _startPageViewModel;
public StartPageViewModel StartPageViewModel
{
get => _startPageViewModel;
set => SetProperty(ref _startPageViewModel, value);
}
private AnotherPageViewModel _anotherPageViewModel;
public AnotherPageViewModel AnotherPageViewModel
{
get => _anotherPageViewModel;
set => SetProperty(ref _anotherPageViewModel, value);
}
public MainWindowViewModel()
{
StartPageViewModel = new StartPageViewModel();
AnotherPageViewModel = new AnotherPageViewModel();
CurrentWorkspace = StartPageViewModel;
}
// Navigation Method
private void NavigateToStartPage()
{
if (CurrentWorkspace != StartPageViewModel)
CurrentWorkspace = StartPageViewModel;
}
// Navigation Method
private void NavigateToAnotherPage()
{
if (CurrentWorkspace != AnotherPageViewModel)
CurrentWorkspace = AnotherPageViewModel;
}
:
<Window ...
xmlns:vm="clr-namespace:App.ViewModels"
xmlns:vw="clr-namespace:App.Views"
... >
<Window.DataContext>
<vm:MainWindowViewModel />
</Window.DataContext>
<Grid>
<ContentControl x:Name="ContentControlMainWindow"
Content="{Binding CurrentWorkspace}"
VerticalAlignment="Stretch">
<ContentControl.Resources>
<DataTemplate x:Key="start_page_view"
DataType="{x:Type vm:StartPageViewModel}">
<vw:StartPage />
</DataTemplate>
<DataTemplate x:Key="another_page_view"
DataType="{x:Type vm:AnotherPageViewModel}">
<vw:AnotherPage />
</DataTemplate>
</ContentControl.Resources>
</ContentControl>
</Grid>
</Window/>
あなたは、あなたが好きにCurrentWorkspace
を設定することができます
WPFのナビゲーションの概念を参照してください。 – Aybe