Igo*_*vas 4 .net wpf asynchronous icommand
我在 WPF (.NET 4.0) 中使用 @Stephen-Cleary AsyncCommand 实现,现在我试图找出如何在命令定义期间指定 CanExecute 处理程序。
通常我创建这样的命令:
SaveCommandAsync = AsyncCommand.Create(async token =>
{
//async code
});
Run Code Online (Sandbox Code Playgroud)
我没有看到任何 Create 重载,因此我可以指定 CanExecute 逻辑。
谢谢,
伊戈尔
使用 Stephen Cleary 的Nito.Mvvm.Async项目来实现您的需求。
将 nuget 引用添加到包中:
<package id="Nito.Mvvm.Async" version="1.0.0-eta-05" targetFramework="net45" />
创建 Xaml 绑定:
<Button Content="Toggle" Command="{Binding MyAsyncCommand}"></Button>
创建 CustomAsyncCommand,指定 CanExecute 函数
MyAsyncCommand = new CustomAsyncCommand(AsyncAction, x=> !_isWorking);
在 AsyncAction 中做一些异步工作
private async Task AsyncAction(object obj) {
_isWorking = true;
MyAsyncCommand.OnCanExecuteChanged();
await Task.Delay(2000);
_isWorking = false;
MyAsyncCommand.OnCanExecuteChanged();
}
Run Code Online (Sandbox Code Playgroud)
最后:享受。