如何在 WPF 中使用 RxUI 交互

How to use RxUI interactions in WPF

我正在尝试弄清楚 WPF 中的交互问题。前段时间我遇到了一个问题,我提到我使用了一个命令来调用 Microsoft。Win32.OpenFileDialog。在帮助我解决我的实际问题的过程中,有人建议我使用交互来调用 OpenFileDialog,但我假设它不是命令,但它当时有效,所以我把它推迟到现在。我通读了 https://www.reactiveui.net/docs/handbook/interactions/,我想我有点理解如何创建交互和注册句柄,我只是不知道如何调用交互,比如按下按钮。谁能给我举个例子或给我指出一个已经发布的例子?

通常我会有这样的命令

public static class CommonInteractions
{
   public static Interaction<string, string> SelectFile { get; } = new Interaction<string, string>();
}

public class MyViewModel : ReactiveObject
{
   private string _fileContents;
   public MyViewModel()
   {
      OpenFile = ReactiveCommand.CreateFromTask(async _ => await OpenNiceFile());
   }

   public async Task OpenNiceFile()
   {
      var fileName = await CommonInteractions.SelectFile.Handle("Please Select a Nice File");

      if (string.IsNullOrWhitespace(fileName) || !File.Exists(fileName)) return;

      FileContents = File.ReadAllText(fileName);
   }

   public string FileContents
   {
      get => _fileContents;
      set => this.RaiseAndSetIfChanged(ref _fileContents, value);
   }
   
   ReactiveCommand<Unit, Unit> OpenFile { get; }
}

public class MainWindow
{
   public MainWindow()
   {
      CommonInteractions.SelectFile.RegisterHandle(async interaction =>
      {
         var dlg = new Microsoft.Win32.OpenFileDialog()
         {
            FileName = "Document"; // Default file name
            DefaultExt = ".txt"; // Default file extension
            Filter = "Text documents (.txt)|*.txt"; // Filter files by extension
            Title = interaction.Input;
         };

         // Show open file dialog box
         Nullable<bool> result = dlg.ShowDialog();

         // Process open file dialog box results
         if (result == true)
         {
            // Open document
            string filename = dlg.FileName;
            interaction.SetOutput(filename);
         }
         else 
         {
            interaction.SetOutput(null);
         }
      });
   }
}

所以在这个例子中我有一个静态交互。您可以为每个 view/view 模型进行交互,或者在这种情况下,我为整个应用程序全局注册一个文件句柄。

然后我将注册一个交互处理程序,它将调用您的打开文件对话框。

在 ViewModel 端我请求一个文件名,如果为 null 我什么都不做,否则打开文件内容。