WPF MVVM:MainWindow导航
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了WPF MVVM:MainWindow导航相关的知识,希望对你有一定的参考价值。
我有一个包含一个窗口的WPF应用程序。只有抛出此窗口,用户才能在应用程序中执行导航。
应用程序结构是:
- 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()
}
如您所见,在应用程序初始化时,我将StartPage视图加载到CurrentWorkspace。现在从StartPageViewModel我需要将CurrentWorkspace内容更改为另一个视图。基本上我很难从应用程序的每个部分控制(和更改)此CurrentWorkspace。
答案
我喜欢这种方法:
在MainWindowViewModel.cs中:
// 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;
}
在MainWindow.xaml中:
<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
设置为您想要的任何内容。例如,如果你想处理StartPageViewModel
的实例,你可以设置StartPageViewModel = null;
。
通常认为在您的ViewModel中使用UI元素(例如ContentControl
)违反了MVVM。
以上是关于WPF MVVM:MainWindow导航的主要内容,如果未能解决你的问题,请参考以下文章