0

我正在 Avalonia 中创建一个简单的概念验证 UI。单击按钮以访问所选文件的内容并在文本框中显示文件的路径时,我需要使用 OpenFileDialog。

我创建了异步任务方法来打开文件对话框并将所选文件保存为字符串,然后将任务传递给按钮事件处理程序。当应用程序运行并单击按钮时,文件对话框打开,但是当文件打开或文件对话框窗口关闭时,文件对话框重新打开而不更新文本框。

相关控制:

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

代码隐藏:

public class MainWindow : Window
{
   public MainWindow()
   {
      InitializeComponent();
      this.DataContext = new TxtViewModel() { Path = @"C:\..." };
#if DEBUG
      this.AttachDevTools();
#endif
   }

   private void InitializeComponent()
   {
      AvaloniaXamlLoader.Load(this);
   }

   public async Task<string> GetPath()
   {
      OpenFileDialog dialog = new OpenFileDialog();
      dialog.Filters.Add(new FileDialogFilter() { Name = "Text", Extensions =  { "txt" } });

      string[] result = await dialog.ShowAsync(this);

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

      return string.Join(" ", result);
   }

   public async void Browse_Clicked(object sender, RoutedEventArgs args)
   {
      string _path = await GetPath();

      var context = this.DataContext as TxtViewModel;
      context.Path = _path;
   }
}

查看型号:

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

我想要完成的是当单击浏览按钮时,调用 GetPath() 任务方法并打开文件对话框,允许用户选择文本文件。选择文件后,文件对话框关闭,文本框绑定更新以显示所选文件的路径。后来我想让它把文本文件的内容保存到一个字符串中,但我希望它首先工作。

What is actually happening is when Browse button is clicked, file dialog opens but when a file is selected or file dialog is closed/canceled it reopens without updating the text box binding Path.

我对 Avalonia 和 WPF 都是新手,所以如果有的话,我愿意使用更好的方法来实现这一点。

4

1 回答 1

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

您在打开导致await dialog.ShowAsync(this);无限期调用的对话框后递归调用您的函数。

于 2019-06-14T20:53:49.647 回答