一个简单的 ReactiveUI 示例:
1.- 创建一个新的 Winforms 项目 (.net 4.5)
2.- 添加 reactiveui-winforms nuget 包 (7.4.0)
3.- 添加一个名为“MainViewModel”的新类并添加此引用:
using System;
using System.Reactive;
using System.Threading.Tasks;
using ReactiveUI;
4.- 这是课程代码:
public class MainViewModel : ReactiveObject
{
private bool canExecute;
private string textButton;
public MainViewModel()
{
this.CanExecute = true;
this.TextButton = "Press me"
// the command creation, this.WhenAnyValue(x => x.CanExecute) is an observable that will change the enabled/disabled command when CanExecute changes
this.AsyncProcess = ReactiveCommand.CreateFromTask(AsyncProcessImpl, this.WhenAnyValue(x => x.CanExecute));
}
public bool CanExecute
{
get { return this.canExecute; }
set { this.RaiseAndSetIfChanged(ref this.canExecute, value); }
}
public string TextButton
{
get { return textButton; }
set { this.RaiseAndSetIfChanged(ref textButton, value); }
}
public ReactiveCommand<Unit, Unit> AsyncProcess { get; }
private async Task AsyncProcessImpl()
{
// changing CanExecute to false will disable the button
this.CanExecute = false;
this.TextButton = "Wait..."
await Task.Delay(TimeSpan.FromSeconds(5)); // just for testing
// CanExecute back to true, the button will be enabled
this.CanExecute = true;
this.TextButton = "Press me";
}
}
5.- 打开 Form1 表单并添加一个名为“btnStart”的按钮。
6.- 打开后面的Form1代码,添加对ReactiveUI的引用:
using ReactiveUI;
7.- 将类更改为:
public partial class Form1: Form, IViewFor<MainViewModel>
{
public Form1()
{
InitializeComponent();
// ViewModel initialization
this.ViewModel = new MainViewModel();
// binding creation when the form is activated
this.WhenActivated(dispose => {
// the command binding will be disposed when the form is deactivated, no memory leaks
dispose(this.BindCommand(this.ViewModel, x => x.AsyncProcess, x => x.btnStart));
dispose(this.OneWayBind(this.ViewModel, x => x.TextButton, x => x.btnStart.Text);
});
}
public MainViewModel ViewModel { get; set; }
object IViewFor.ViewModel
{
get { return this.ViewModel; }
set { this.ViewModel = value as MainViewModel; }
}
}
8.- 运行应用程序
编辑:如果你想改变哪个事件会触发命令,只需在 BindCommand 方法中添加最后一个参数:
dispose(this.BindCommand(this.ViewModel, x => x.AsyncProcess, x => x.btnStart, "TheEventNameYouWant"));
您可以将命令绑定到具有 Disable 属性的任何控件,只需使用将引发命令的事件的名称。