mvvm 并不难。在您的情况下,您首先需要一个主视图模型。
public class MainViewModel
{
private ICollectionView _myView {get;set;}
public ObservableCollection<MyModulWrapper> MyModules{get;set;}
public MyModulWrapper SelectedModul {get;set;}
public MainViewModel()
{
this.MyModules = new ObservableCollection<MyModulWrapper>();
//i use icollectionview because i often need sorting or filtering
this._myView = = CollectionViewSource.GetDefaultView(this.MyModules);
this._myView .CurrentChanged += (s, e) => { this.SelectedModul = this._myView .CurrentItem as MyModulWrapper; };
}
}
您必须使用您想在顶部屏幕上显示的所有模块(视图模型)填充(以任何方式 - 我将 mef 用于我的应用程序,但对其进行硬编码也可以)。
MyModulWrapper 只包含您的模块的视图模型和一个不错的导航显示名称。
public class MyModulWrapper
{
public string Displayname {get;set;}
public object Modul {get;set;}//instead of object you can take an interface or base class or whatever
}
现在您可以让主视图运行了 :) 您只需将 MainWindow 的数据上下文设置为您的 MainViewModel。
mainwindow.xaml
<Window.Resources>
<!--for each viewmodel you wanna show create a datatemplate. so wpf knows how to render your viewmodel-->
<DataTemplate DataType={x:Type local:MyViewmodel4FirstButton>
<local:MyFirstButtonView />
</DataTemplate>
</Window.Resources>
<!-- for navigation -->
<ListBox ItemsSource="{Binding MyModules}"
SelectedItem="{Binding SelectedModul , Mode=OneWay}"
IsSynchronizedWithCurrentItem="true">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Displayname}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<!-- all you need to show your selected modul - if you have a DATATEMPLATEs!! -->
<ContentControl Content="{Binding SelectedModul }"/>
当然,您所有的视图模型都必须实现 INotifyPropertyChanged,并正确提升它。
ps:代码是在没有 IDE 的情况下编写的,所以忽略错误^^