winform MVVM ReactiveUI

ReactiveUI是实现了MVVM模式的框架,它的核心目标是能够在ViewModel中相关属性发生变化时能够可执行相应的命令。ReactiveUI支持Xamarin、WPF、WinForm、Windows Phone、UWP。这里咱们选择WinForm对应的版本ReactiveUI.WinForms。
选择“管理NuGet程序包”,在打开的窗口中选择“浏览”,并搜索ReactiveUI.WinForms进行安装
1.在项目目录下新建文件夹ViewModel,并在文件夹下新建一个PersonViewModel类,写入以下代码:函数
2.须要继承自ReactiveObject
public class PersonViewModel : ReactiveObject
{
private int _id;
public int Id
{
get { return _id; }
set
{
this.RaiseAndSetIfChanged(ref _id, value);
}
}

    private string _name;
    public string Name
    {
        get { return _name; }
        set
        {
            this.RaiseAndSetIfChanged(ref _name, value);
        }
    }

    private int _age;
    public int Age
    {
        get { return _age; }
        set
        {
            this.RaiseAndSetIfChanged(ref _age, value);
        }
    }

}

3.新建Form1窗口 在窗体上拖入3个textbox和3个label控件
4.视图窗体须要实现IViewFor接口,并且须要绑定的ViewModel类(本例中的ViewModel是PersonViewModel)做为泛型传入接口
public partial class Form1 : Form, IViewFor
{
public PersonViewModel ViewModel { get; set; }
public Form1()
{
InitializeComponent();
this.WhenActivated(a =>
{
a(this.Bind(ViewModel, vm => vm.Id, v => v.textBox1.Text));
a(this.Bind(ViewModel, vm => vm.Name, v => v.textBox2.Text));
a(this.Bind(ViewModel, vm => vm.Age, v => v.textBox3.Text));
a(this.OneWayBind(ViewModel, vm => vm.Id, v => v.label1.Text));
a(this.OneWayBind(ViewModel, vm => vm.Name, v => v.label2.Text));
a(this.OneWayBind(ViewModel, vm => vm.Age, v => v.label5.Text));
});
ViewModel = new PersonViewModel();
}

    object IViewFor.ViewModel
    {
        get { return ViewModel; }
        set { ViewModel = (PersonViewModel)value; }
    }

}

这样运行程序,在控件中输入值 标签也会同步修改数据

posted @ 2024-04-15 12:47  .Net菜鸟站  阅读(153)  评论(0编辑  收藏  举报