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));
});