首先,您不需要任何这些工具包/框架来实现 MVVM。它可以像这样简单......让我们假设我们有一个MainViewModel,和PersonViewModel和一个CompanyViewModel,每个都有自己的相关视图并且每个都扩展了一个abstract基类BaseViewModel。
在BaseViewModel中,我们可以添加通用属性和/或ICommand实例并实现INotifyPropertyChanged接口。由于它们都扩展了BaseViewModel类,我们可以在类中拥有这个属性MainViewModel,可以将其设置为我们的任何视图模型:
public BaseViewModel ViewModel { get; set; }
当然,与这个快速示例不同,您将在属性INotifyPropertyChanged上正确实现接口。现在,我们声明了一些简单的 s 来连接视图和视图模型:App.xamlDataTemplate
<DataTemplate DataType="{x:Type ViewModels:MainViewModel}">
<Views:MainView />
</DataTemplate>
<DataTemplate DataType="{x:Type ViewModels:PersonViewModel}">
<Views:PersonView />
</DataTemplate>
<DataTemplate DataType="{x:Type ViewModels:CompanyViewModel}">
<Views:CompanyView />
</DataTemplate>
现在,无论我们BaseViewModel在应用程序中使用我们的哪个实例,这些DataTemplates 都会告诉框架显示相关视图。我们可以这样显示它们:
<ContentControl Content="{Binding ViewModel}" />
所以我们现在需要做的就是切换到一个新的视图是ViewModel从类中设置属性MainViewModel:
ViewModel = new PersonViewModel();
最后,我们如何从其他视图中改变视图?那么有几种可能的方法可以做到这一点,但最简单的方法是将Binding子视图中的 a 直接添加ICommand到MainViewModel. 我使用自定义版本的RelayComand,但你可以使用任何你喜欢的类型,我猜你会得到图片:
public ICommand DisplayPersonView
{
get { return new ActionCommand(action => ViewModel = new PersonViewModel(),
canExecute => !IsViewModelOfType<Person>()); }
}
在子视图 XAML 中:
<Button Command="{Binding DataContext.DisplayPersonView, RelativeSource=
{RelativeSource AncestorType={x:Type MainView}}, Mode=OneWay}" />
而已!享受。