I am creating a simple proof of concept UI in Avalonia. I need to use OpenFileDialog
when a button is clicked to access the contents of the chosen file and show the path to the file in a textbox.
I've created asynchronous Task<string>
method to open the file dialog and save the selected file as a string, then pass the task to a button event handler. When the app is run and the button is clicked, file dialog opens, but when a file is opened or the file dialog window is closed, file dialog reopens without updating the text box.
Relevant Controls:
<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" />
Code-behind:
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;
}
}
View Model:
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));
}
}
What I am trying to accomplish is when Browse button is clicked, the GetPath()
Task method is called and opens file dialog allowing the user to choose a text file. After choosing a file, file dialog closes and the text box binding updates to show the path of the chosen file. Later I'd like it to have it save the contents of the text file to a string, but I want this to work first.
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.
I am new to both Avalonia and WPF, so I am open to using a better way of accomplishing this if there is one.
if (result != null)
{
await GetPath();
}
You are calling your function recursively after opening the dialog which leads to calling await dialog.ShowAsync(this);
indefinitely.