jpmikkers / Baksteen.Avalonia.Blazor

Build Avalonia-Blazor hybrid desktop apps using this Blazor webview component for Avalonia
MIT License
117 stars 9 forks source link

In this project ,is there any way to open file dialog from blazor to Avalonia? #8

Closed hanxiao123 closed 7 months ago

hanxiao123 commented 7 months ago

In this project ,is there any way to open file dialog from blazor to Avalonia? I'm trying <button @onclick="OpenFile" /> "OpenFile" visual cannot pass to service from MainWindow.

private async Task OpenFile() { var topLevel = TopLevel.GetTopLevel(visual); // Start async operation to open the dialog. var files = await topLevel.StorageProvider.OpenFilePickerAsync(new FilePickerOpenOptions { Title = "Open Text File", AllowMultiple = false });

if (files.Count >= 1) { // Open reading stream from the first file. await using var stream = await files[0].OpenReadAsync(); using var streamReader = new StreamReader(stream); // Reads all the content of file as a text. var fileContent = await streamReader.ReadToEndAsync(); } }

jpmikkers commented 7 months ago

Hi, the trick is to always wrap any functions you need from Avalonia inside a service class, then inject that into the blazor page to use it. I created a demo for this in my mvvmct branch, see commit 8a49b3f5e0b7258f4e41cfe84b8905cc6b31f4a1 (add avalonia-blazor file picker interop demo)

hanxiao123 commented 7 months ago

that's great!you're awsome!