WinForm中简单的MVVM模式使用方法

基本写法和wpf有点类似,但是比wpf略微简单

简单案例

viewModel的实现

  1. 这是viewmodel的基类,注意其中方法参数的CallerMemberName标记,这个特性标记的作用是自动传入调用者(方法或属性)名称
1
2
3
4
5
6
7
8
9
public class ViewModelBase:INotifyPropertyChanged
{
public event PropertyChangedEventHandler? PropertyChanged;

protected void Notify([CallerMemberName]string? name = null)
{
PropertyChanged.Invoke(this,new PropertyChangedEventArgs(name));
}
}
  1. 案例实现
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
public class Form1ViewModel: ViewModelBase
{
private int _count;

public ICommand ChangeCountCommand { get; set; }

public Form1ViewModel()
{
CanChangeCount = _ => true;
ChangeCount = (count) => Count++;
ChangeCountCommand = new RelayCommand(CanChangeCount,ChangeCount);
}

public Func<object,bool> CanChangeCount { get; set; }

public Action<object> ChangeCount { get; set; }

public int Name
{
get
{
return _count;
}
set
{
if(value != _count)
{
_count = value;
Notify();
}
}
}
}

进行绑定

  1. 在Form的设计表单当中拖入BindingSource,并设置其数据源为ViewModel,此处要特别注意数据源的类型,通常需要查看自动生成的设计器当中生成的代码
  2. 在需要绑定的组件当中的DataBinding部分的高级窗口设置相应属性(比如命令、属性名等)即可