Avalonia 中的 OpenFileDialog - ShowAsync 出错

OpenFileDialog in Avalonia - Error with ShowAsync

背景:

我一直在用Avalonia开发一个跨平台的UI。为了学习它,我正在尝试创建一个简单的程序,该程序使用 OpenFileDialog 打开一个 .txt 文件并在另一个 window.

中显示其内容在 ComboBox

我正在尝试编写一个方法来打开文件对话框和 returns 用户打开的路径。我正在使用带有 Click 事件的按钮打开文件对话框,并将指定路径放在 TextBox 中供用户查看。由于我是 WPF 和 Avalonia 的新手,所以我不确定如何进行。

问题:

我已经创建了 UI 视图和视图模型。 view model使用INotifyPropertyChangedTextBox中显示选中的文件路径,我默认设置为C盘

现在我想使用 OpenFileDialog 将该路径更新为用户选择的 .txt 文件的路径。我找到了一个演示 OpenFileDialog 的示例,但它似乎对我不起作用,我也不太明白它应该如何工作。

TxtView.xaml:

<TextBox Text="{Binding Path}" Margin="0 0 5 0" Grid.Column="0" IsReadOnly="True" />
<Button Content="Browse" Click="OnBrowseClicked" Margin="0 0 0 0" Grid.Column="1" />

TxtView.xaml.cs:

public async Task GetPath()
{
   var dialog = new OpenFileDialog();
   dialog.Filters.Add(new FileDialogFilter() { Name = "Text", Extensions = { "txt" } });
   dialog.AllowMultiple = true;

   var result = await dialog.ShowAsync();

   if (result != null)
   {
      await GetPath(result);
   }
}

public void OnBrowseClicked(object sender, RoutedEventArgs args)
{
   var context = this.DataContext as TxtViewModel;
   context.Path = "path";
}

TxtViewModel.cs

class TxtViewModel : INotifyPropertyChanged
{
   private string _path;

   public string Path
   {
      get => _path;
      set
      {
         if (value != _path)
         {
            _path = value;
            OnPropertyChanged();
         }
      }
   }  

   public event PropertyChangedEventHandler PropertyChanged;

   protected virtual void OnPropertyChanged([CallerMemberName] string 
   propertyName = null)
   {
      PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
   }

}

我在使用此代码时遇到的错误是 TxtView.xaml.cs 文件中的 ShowAsync()。错误说

There is no argument given that corresponds to the required formal parameter 'parent' of 'OpenFileDialog.ShowAsync(Window)'

我已经尝试 ShowAsync(this) 修复了 ShowAsync 的错误,但现在给了我错误

Arguement 1: cannot convert from 'Txt2List.Views.TxtView' to 'Avalonia.Controls.Window'

感谢所有帮助,如果我不清楚,我深表歉意,我对 Avalonia、WPF 和 XAML 是全新的,所以我正在学习。如果我可以提供其他信息,请告诉我。

dialog.ShowAsync(); 有一个 Window parent 参数,目前是强制性的。您可能使用的是过时的 Avalonia 版本 (0.7),方法签名中未指定它。

您可以通过调用 (Window)control.GetVisualRoot()

获取映射控件的 Window