前言
为了解决WPF UI与程序逻辑之间得到解耦,所以使用Microsoft.Toolkit.Mvvm框架来实现,说真的开发逻辑真的有些不适应,不过理解就好。框架大体支持ICommand、IMessenger等。
MVVM是Model-View-ViewModel的简写。它本质上就是MVC (Model-View- Controller)的改进版。即模型-视图-视图模型。分别定义如下:
MVVM示意图如下所示

一、导入包


二、使用框架实现

"myMVVM.MainWindow" - xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
- xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
- xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
- xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
- xmlns:local="clr-namespace:myMVVM"
- mc:Ignorable="d"
- Title="MainWindow" Height="450" Width="800">
-
-
"Left" Margin="145,52,0,0" TextWrapping="Wrap" Text="{Binding Name}" VerticalAlignment="Top" Width="517" Height="189"/> -
-
-

- using Microsoft.Toolkit.Mvvm.Messaging;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using System.Windows;
- using System.Windows.Controls;
- using System.Windows.Data;
- using System.Windows.Documents;
- using System.Windows.Input;
- using System.Windows.Media;
- using System.Windows.Media.Imaging;
- using System.Windows.Navigation;
- using System.Windows.Shapes;
-
- namespace myMVVM
- {
- ///
- /// Interaction logic for MainWindow.xaml
- ///
- public partial class MainWindow : Window
- {
- public MainWindow()
- {
- InitializeComponent();
- this.DataContext = new MainViewModel();
- WeakReferenceMessenger.Default.Register<string, string>(this, "Token1", (s, val) =>
- {
- MessageBox.Show(val);
- });
- }
-
- }
- }

- using Microsoft.Toolkit.Mvvm.ComponentModel;
- using Microsoft.Toolkit.Mvvm.Input;
- using Microsoft.Toolkit.Mvvm.Messaging;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using System.Windows;
-
- namespace myMVVM
- {
- internal class MainViewModel: ObservableObject
- {
- ///
- /// 供前端的Command命令Binding调用
- ///
- public RelayCommand ShowCommand { get; set; }
- public MainViewModel()
- {
- ShowCommand = new RelayCommand(Show);
- }
- private string name;
- public string Name
- {
- get { return name; }
- set { name = value; OnPropertyChanged(); }
- }
- private string title;
- public string Title
- {
- get { return title; }
- set { title = value; OnPropertyChanged(); }
- }
-
- public void Show()
- {
- Title = "你点击了按钮 this is Title";
- Name = "你点击了按钮 this is Name";
- MessageBox.Show(Name);
- WeakReferenceMessenger.Default.Send<string, string>(Title, "Token1");
- }
- }
- }


总结:
这样当我们的业务代码逻辑变更时就不用考虑ui的修改,需要习惯这个逻辑。