1、将App.xaml中的StartupUri="MainWindow.xaml"删除。
2、使用NuGet安装Prism.Wpf、Prism.Core、Prism.Unity。
3、添加类“Bootstrapper”,编辑如下:
1 using Microsoft.Practices.Unity; 2 using Prism.Unity; 3 using System.Windows; 4 using BootstrapperShell.Views; 5 6 namespace BootstrapperShell 7 { 8 public class Bootstrapper : UnityBootstrapper 9 {10 protected override DependencyObject CreateShell()11 {12 return Container.Resolve();13 }14 15 protected override void InitializeShell()16 {17 Application.Current.MainWindow.Show();18 }19 }20 }
4、创建文件夹Views,将MainWindow.xaml移动到此文件夹中。创建文件夹ViewModels,新建类MainWindowViewModel.cs。注意:VM类的名称一定是V+“ViewModel”,例如MainWindow+“ViewModel”。
111 12 1913 14 15 16 17 18
1 using System; 2 using Prism.Commands; 3 using Prism.Mvvm; 4 5 namespace UsingDelegateCommands.ViewModels 6 { 7 public class MainWindowViewModel:BindableBase 8 { 9 private bool _isEnabled;10 public bool IsEnabled11 {12 get { return _isEnabled; }13 set14 {15 SetProperty(ref _isEnabled, value);16 //增加执行监控17 ExecuteDelegateCommand.RaiseCanExecuteChanged();18 }19 }20 21 private string _updateText;22 public string UpdateText23 {24 get { return _updateText; }25 set { SetProperty(ref _updateText, value); }26 }27 28 public DelegateCommand ExecuteDelegateCommand { get; private set; }29 public DelegateCommandExecuteGenericDelegateCommand { get; private set; }30 public DelegateCommand DelegateCommandObservesProperty { get; private set; }31 public DelegateCommand DelegateCommandObservesCanExecute { get; private set; }32 33 public MainWindowViewModel()34 {35 ExecuteDelegateCommand = new DelegateCommand(Execute, CanExecute);36 37 DelegateCommandObservesProperty = new DelegateCommand(Execute, CanExecute).ObservesProperty(() => IsEnabled);38 39 DelegateCommandObservesCanExecute = new DelegateCommand(Execute).ObservesCanExecute(() => IsEnabled);40 41 ExecuteGenericDelegateCommand = new DelegateCommand (ExecuteGeneric).ObservesCanExecute(() => IsEnabled);42 }43 44 private void Execute()45 {46 UpdateText = $"Updated:{DateTime.Now}";47 }48 49 private void ExecuteGeneric(string parameter)50 {51 UpdateText = parameter;52 }53 54 private bool CanExecute()55 {56 return IsEnabled;57 }58 }59 }
5、修改App.xaml
1 using System.Collections.Generic; 2 using System.Configuration; 3 using System.Data; 4 using System.Linq; 5 using System.Threading.Tasks; 6 using System.Windows; 7 8 namespace BootstrapperShell 9 {10 ///11 /// App.xaml 的交互逻辑12 /// 13 public partial class App : Application14 {15 protected override void OnStartup(StartupEventArgs e)16 {17 base.OnStartup(e);18 19 var bootstrapper = new Bootstrapper();20 bootstrapper.Run();21 }22 }23 }
6、最终结果: