77 lines
2.2 KiB
C#

using System;
using System.Threading.Tasks;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Interactivity;
using Avalonia.Threading;
using Avalonia.Platform.Storage;
using XSDVisualiser.Core;
using XSDVisualiser.Models;
using XSDVisualiser.Desktop.ViewModels;
namespace XSDVisualiser.Desktop.Views;
public partial class HeaderView : UserControl
{
private readonly Button? _openBtn;
public HeaderView()
{
InitializeComponent();
_openBtn = this.FindControl<Button>("OpenBtn");
if (_openBtn != null)
{
_openBtn.Click += OpenBtn_Click;
}
}
private async void OpenBtn_Click(object? sender, RoutedEventArgs e)
{
if (TopLevel.GetTopLevel(this) is not Window topLevel)
return;
var storageProvider = topLevel.StorageProvider;
var options = new FilePickerOpenOptions
{
AllowMultiple = false,
Title = "Open XSD file",
FileTypeFilter =
[
new FilePickerFileType("XSD schema")
{
Patterns = ["*.xsd"]
}
]
};
var results = await storageProvider.OpenFilePickerAsync(options);
if (results.Count <= 0) return;
var file = results[0];
var path = file.TryGetLocalPath();
if (!string.IsNullOrEmpty(path))
{
await ParseAndShowAsync(path!, topLevel);
}
else
{
Dispatcher.UIThread.Post(() => topLevel.DataContext = new MainWindowViewModel(new SchemaModel { TargetNamespace = "Selected file is not a local file. Please choose a local .xsd." }));
}
}
private Task ParseAndShowAsync(string path, Window hostWindow)
{
return Task.Run(() =>
{
try
{
var parser = new XsdSchemaParser();
var model = parser.Parse(path);
Dispatcher.UIThread.Post(() => hostWindow.DataContext = new MainWindowViewModel(model));
}
catch (Exception ex)
{
Dispatcher.UIThread.Post(() => hostWindow.DataContext = new MainWindowViewModel(new SchemaModel { TargetNamespace = ex.Message }));
}
});
}
}