1

我想注册一个打开文件并处理它的异步命令。

OpenFileCommand = new ReactiveAsyncCommand();
OpenFileCommand.RegisterAsyncAction(_ =>
{
    var path = GetOpenFilePath(); // This needs to be on the UI thread
    if (String.IsNullOrEmpty(path))
        return;

    ProcessFile(path);
});

类似于这个问题

带用户确认的异步命令执行

但我不确定如何在这里应用该答案。我需要将路径值传递给处理器。

我该怎么做?

4

1 回答 1

3

hack 方法是在 ViewModel 中创建 OpenFileCommand,但RegisterAsyncAction在 View 中调用,这有点恶心。

您可以做的另一件事是将一个接口注入到 ViewModel 中,该接口代表通用文件对话框(即打开文件选择器)。从测试的角度来看,这非常棒,因为您可以模拟用户做各种事情。我将其建模为:

public interface IFileChooserUI
{
    // OnError's if the user hits cancel, otherwise returns one item
    // and OnCompletes
    IObservable<string> GetOpenFilePath();
}

现在,您的 async 命令变为:

OpenFileCommand.RegisterAsyncObservable(_ => 
    fileChooser.GetOpenFilePath()
        .SelectMany(x => Observable.Start(() => ProcessFile(x))));

或者,如果你想摆脱等待(如果你使用的是 RxUI 4.x 和 VS2012,你可以):

OpenFileCommand.RegisterAsyncTask(async _ => {
    var path = await fileChooser.GetOpenFilePath();
    await Task.Run(() => ProcessFile(path));
});
于 2013-04-13T23:31:42.023 回答