[超级简单入门]c# .net ReactiveUI RX.Net Winform MVVM 双向绑定示例
3个Nuget包
<ItemGroup>
<PackageReference Include="ReactiveUI" Version="16.2.6" />
<PackageReference Include="ReactiveUI.Fody" Version="16.2.6" />
<PackageReference Include="ReactiveUI.WinForms" Version="16.2.6" />
</ItemGroup>
界面拖3个控件
using ReactiveUI;
using ReactiveUI.Fody.Helpers;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.DirectoryServices;
using System.Drawing;
using System.Linq;
using System.Reactive.Concurrency;
using System.Reactive.Linq;
using System.Reactive.Subjects;
using System.Reflection.Emit;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Windows.Input;
namespace RxNetTest1
{
public partial class Form1 : Form, IViewFor<ShellViewModel>
{
public Form1()
{
InitializeComponent();
ViewModel = new ShellViewModel();
this.Bind(ViewModel, x => x.Text1, x => x.textBox1.Text);
this.Bind(ViewModel, x => x.Text1, x => x.button1.Text);
this.Bind(ViewModel, x => x.Text1, x => x.label1.Text);
this.BindCommand(ViewModel, x => x.OKCmd, x => x.button1);
}
public ShellViewModel ViewModel { get; set; }
object IViewFor.ViewModel
{
get => ViewModel;
set => ViewModel = (ShellViewModel)value;
}
}
}
ShellViewModel.cs
using ReactiveUI;
using ReactiveUI.Fody.Helpers;
namespace RxNetTest1
{
public class ShellViewModel : ReactiveObject
{
public ShellViewModel()
{
OKCmd = ReactiveCommand.Create(() => { Count++; Text1 = Text1.Split('-')[0].Trim() + " - " + Count; }
, this.WhenAny(vm => vm.Count, s => Count >=0));
}
[Reactive]
public int Count { get; set; } = 0;
[Reactive]
public string Text1 { get; set; } = "测试文字";
public ReactiveCommand<System.Reactive.Unit, System.Reactive.Unit> OKCmd { get; set; }
}
}
双向绑定演示效果