public class MainViewModel : ViewModelBase
{
//add instances to all the ViewModels you want to switch between here, and add templates for them in your resources specifying the x:type and the view or data template to be used
public ObservableCollection<ViewModelBase> ViewModels { get; set; } = new ObservableCollection<ViewModelBase>();
private ViewModelBase _currentViewModel;
public ViewModelBase CurrentViewModel {
get { return _currentViewModel; }
set { SetField(ref _currentViewModel, value); }
}
private ICommand _nextViewModel;
public ICommand NextViewModel
{
get
{
return _nextViewModel = _nextViewModel ?? new RelayCommand(p =>
{
CurrentViewModel = ViewModels[ViewModels.IndexOf(CurrentViewModel) +1];
}, p =>
{
return ViewModels.IndexOf(CurrentViewModel) + 1 != ViewModels.Count && CurrentViewModel != null;
});
}
}
public ICommand _prevViewModel;
public ICommand PrevViewModel
{
get
{
return _prevViewModel = _prevViewModel ?? new RelayCommand(p =>
{
CurrentViewModel = ViewModels[ViewModels.IndexOf(CurrentViewModel) - 1];
}, p =>
{
return ViewModels.IndexOf(CurrentViewModel) != 0 && CurrentViewModel!=null;
});
}
}
private ICommand _switchToViewModel;
public ICommand SwitchToViewModel
{
get
{
return _switchToViewModel = _switchToViewModel ?? new RelayCommand(p =>
{
CurrentViewModel = this.ViewModels.FirstOrDefault(vm=>vm.GetType()==p as Type);
}, p =>
{
return this.ViewModels.FirstOrDefault(vm => vm.GetType() != p as Type) != null;
});
}
}
}
2 回答
使用Prism Navigation非常容易,并且它不需要您在ViewModel上创建依赖项,或者使用动态DataTemplates引入性能滞后 . 我建议阅读Prism导航文档 .
https://github.com/PrismLibrary/Prism/blob/master/Documentation/WPF/60-Navigation.md#view-based-navigation
基本上你使用ReqestNavigate,GoBack和GoForward的组合 .
您还可以在此学习样本:
https://github.com/PrismLibrary/Prism-Samples-Wpf/tree/master/View-Switching%20Navigation_Desktop
您还应该观看这个课程,它将引导您完全了解您的要求:
https://app.pluralsight.com/library/courses/prism-introduction/table-of-contents
我有一个我很久以前写过的例子,并且它不需要任何框架废话,根据我的经验,WPF MVVM框架在大多数情况下是无用的,并且往往使简单的事情复杂化,你需要的是
ICommand
实现和ViewModelBase
实现INotiftyPropertyChanged
,这是一个简单的插图:XML:
鉴于上述情况,
CurrentViewModel
属性发生变化时,将根据DataTemplate
资源选择View,并将Window的DataContext设置为MainViewModel
.主ViewModel如下所示:
结果看起来像