Prism框架下MVVM模式中命令实现
前言
命令在MVVM模式中非常重要,本文就来讲解如何在Prism框架下实现MVVM模式中的命令。
1、新建ViewModel类
使用DelegateCommand类来实例化ICommand接口,这里以最小化窗口为例,CommandMinWindow 命令绑定的方法MinWindow中将属性ShellWindowState设置为 WindowState.Minimized;
[Export(typeof(ViewModel))]public class ViewModel : BindableBase{private IRegionManager regionManager;private IEventAggregator eventAggregator;[ImportingConstructor]public ViewModel(IRegionManager _regionManager, IEventAggregator _eventAggregator){this.regionManager = _regionManager;InitialCommand();eventAggregator = _eventAggregator;}public ICommand CommandWindowLoaded { get; set; }public ICommand CommandMinWindow { get; set; }public ICommand CommandZoonWindow { get; set; }public ICommand CommandExitApplication { get; set; }private void InitialCommand(){CommandWindowLoaded = new DelegateCommand<System.Windows.Window>(WindowLoaded);CommandMinWindow = new DelegateCommand(MinWindow);CommandZoonWindow = new DelegateCommand(ZoomWindow);CommandExitApplication = new DelegateCommand(ExitApplication);}private WindowState shellWindowState;public WindowState ShellWindowState{get { return shellWindowState; }set { SetProperty(ref shellWindowState, value); }}private void WindowLoaded(System.Windows.Window obj){}private void MinWindow(){ShellWindowState = WindowState.Minimized;}private void ZoomWindow(){ShellWindowState = ShellWindowState == WindowState.Maximized ? WindowState.Normal : WindowState.Maximized;}private void ExitApplication(){MessageBoxResult result = System.Windows.MessageBox.Show("您需要退出程序吗?", "提示", MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.No);if (result == MessageBoxResult.Yes){Process.GetCurrentProcess().Kill();}}}
2、设置DataContext属性的值
我们在MVVM模式中主要就是指定Binding的源是DataContext属性,这里DataContext属性的值就是ViewModel类的对象,这里使用Mef的Import特性将ViewModel对象通过属性注入的方式赋值给DataContext属性
3、建立命令绑定关系
设置Command的值,使用Binding绑定ViewModel类中的CommandMinWindow命令,这里的CommandMinWindow就是ViewModel类中的已经实例化的ICommand接口。
<Button Margin="0 5 3 0" Command="{Binding CommandMinWindow}" Content="最小化" Height="25" Width="40" Background="Red" BorderThickness="0">
4、执行
当我们点击按钮”最小化“,这时MinWindow就能执行。
马工撰写的年入30万+C#上位机项目实战必备教程(点击下方链接即可访问文章目录)
1、《C#串口通信从入门到精通》
2、《C#与PLC通信从入门到精通 》
3、《C# Modbus通信从入门到精通》
4、《C#Socket通信从入门到精通 》
5、《C# MES通信从入门到精通》
6、《winform控件从入门到精通》
7、《C#操作MySql数据库从入门到精通》