背景:
我一直在使用 Avalonia 开发跨平台的 UI。为了学习它,我正在尝试创建一个简单的程序,该程序使用 OpenFileDialog 打开一个 .txt 文件并将其内容显示在另一个窗口的 ComboBox 中。
我正在尝试编写一个打开文件对话框并返回用户打开的路径的方法。我正在使用带有 Click 事件的按钮来打开文件对话框,并将指定的路径放在 TextBox 中供用户查看。由于我是 WPF 和 Avalonia 的新手,我不知道如何继续。
问题:
我已经创建了 UI 视图和视图模型。视图模型使用 INotifyPropertyChanged 在 TextBox 中显示选定的文件路径,我将其默认设置为 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() 。错误提示“没有给出与 'OpenFileDialog.ShowAsync(Window)' 的所需形式参数 'parent' 相对应的参数”
我尝试了 ShowAsync(this),它修复了 ShowAsync 的错误,但现在给了我错误“Arguement 1: cannot convert from 'Txt2List.Views.TxtView' to 'Avalonia.Controls.Window'
感谢所有帮助,如果我不清楚,我深表歉意,我对 Avalonia、WPF 和 XAML 完全陌生,所以我正在学习。如果我可以提供其他信息,请告诉我。