学习过程:在WPF学习的过程中,遇到一个1w+多行的WinForm代码需要改写成WPF,我是个WPF菜鸟,代老师向我讲了一个项目中正在使用的架构——MvvmLight。这个架构虽然已经被作者弃用了,但是它已经被广泛应用了多年,并且是轻量级的。菜鸟使用,也不会遇到大问题。资深的WPF选手,一般都会自己写这种架构,代老师就有自己写的架构,有问题,好维护。
首先,需要在NuGet中下载并安装MvvmLight
然后,才是代码范例:
1、MainWindow.xaml代码如下:
<Window x:Class="WpfApp1.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:WpfApp1"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Window.DataContext>
<local:ViewModel/>
</Window.DataContext>
<Grid>
<Button Content="{Binding Model.SaveContent}" Command="{Binding SaveCommand}" IsEnabled="{Binding SaveIsEnabld}" Width="100" Height="25"/>
</Grid>
</Window>
1-1、MainWindow.xaml.cs代码不作任何改动(如果有增加任何代码,则有违三层架构思想)
using System.Windows;
namespace WpfApp1
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
}
}
2、ViewModel.cs代码如下:
using GalaSoft.MvvmLight.Command;
using System.Threading.Tasks;
using System.Windows.Input;
namespace WpfApp1
{
internal class ViewModel
{
public ICommand SaveCommand { get; set; }
public Model Model { get; set; }
public ViewModel()
{
SaveCommand = new RelayCommand(BtnSave_Click);
Model = new Model();
}
private void BtnSave_Click()
{
Model.SaveIsEnable = false;
/*保存事件主体*/
Model.SaveIsEnable = true;
Model.SaveContent = "保存成功";
new Task(() =>
{
System.Threading.Thread.Sleep(500);
Model.SaveContent = "保存";
}).Start();
}
}
}
3、Model.cs代码如下:
using GalaSoft.MvvmLight;
namespace WpfApp1
{
internal class Model : ViewModelBase
{
private string saveContent = "保存";
public string SaveContent { get => saveContent; set => Set(ref saveContent, value); }
private bool saveIsEnable = true;
public bool SaveIsEnable { get => saveIsEnable; set => Set(ref saveIsEnable, value); }
}
}
数据类必须继承ViewModelBase类(using GalaSoft.MvvmLight;),它实现后台数据改变,同步改变用户界面显示的数据。
Model.cs一般用来控制用户操作的数据绑定,如果是其他参数,例如AxisParam.cs,只需要让它按照Model.cs的写法,继承ViewModelBase。然后在ViewModel.cs中建一个属性,构造函数中引用或新建一个实例,就可以实现其他数据绑定。