和之前一样,新建一个WPF工程,Models,Views,ViewModels文件夹,另外添加Selector文件夹。
第一,Selector文件夹中添加TemplateSelectorDemo类
public class TemplateSelectorDemo: DataTemplateSelector { public DataTemplate CalendarDataTemplate { get; set; } public DataTemplate EllipseDataTemplate { get; set; } public DataTemplate RectangleDataTemplate { get; set; } public override DataTemplate SelectTemplate(object item, DependencyObject container) { if (container is FrameworkElement && item != null) { if (item is CalendarViewModel) return CalendarDataTemplate; if (item is EllipseViewModel) return EllipseDataTemplate; if (item is RectangleViewModel) return RectangleDataTemplate; else return null; } return null; } }
ViewModels中添加CalendarViewModel,EllipseViewModel,RectangleViewModel,MenuViewModel类
分别按顺序图如下
Views文件夹中添加CalendarView.xaml,EllipseView.xaml,MenuView.xaml,RectangleView.xaml页面
图片按顺序分别如下
MenuViewModel类中的内容如下
public class MenuViewModel:Screen { public MenuViewModel() { CurrentViewModel =new CalendarViewModel() { }; ViewModelsCollection.Add(CurrentViewModel); CurrentViewModel = new EllipseViewModel() { }; ViewModelsCollection.Add(CurrentViewModel); CurrentViewModel = new RectangleViewModel() { }; ViewModelsCollection.Add(CurrentViewModel); } private Screen _CurrentViewModel; public Screen CurrentViewModel { get { return _CurrentViewModel; } set { Set(ref _CurrentViewModel, value); } } private Screen _SelectedViewModel; public Screen SelectedViewModel { get { return _SelectedViewModel; } set { Set(ref _SelectedViewModel, value); } } private ObservableCollection<Screen> _ViewModelsCollection=new ObservableCollection<Screen>(); public ObservableCollection<Screen> ViewModelsCollection { get { return _ViewModelsCollection; } set { Set(ref _ViewModelsCollection, value); } } }
在添加Bootstrapper类,内容如下图
最后看看运行的效果如下图显示