Files
AvaloniaTest/AvaloniaTest/MainView.axaml.cs
T

89 lines
3.2 KiB
C#

using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Notifications;
using Avalonia.Markup.Xaml;
using Avalonia.Media.Imaging;
using Avalonia.Platform.Storage;
using System;
using System.IO;
using System.Threading.Tasks;
namespace AvaloniaTest
{
public partial class MainView : NavigationPage
{
public static MainView Current { get; private set; } = null!;
private WindowNotificationManager notificationManager = null!;
public MainView()
{
InitializeComponent();
Current = this;
}
protected override void OnAttachedToVisualTree(VisualTreeAttachmentEventArgs e)
{
base.OnAttachedToVisualTree(e);
notificationManager = new WindowNotificationManager(TopLevel.GetTopLevel(this));
}
/// <summary>
/// Показывает уведомление с заданным заголовком, сообщением и типом уведомления.
/// </summary>
/// <param name="title">Заголовок</param>
/// <param name="message">Содержимое</param>
/// <param name="type">Тип уведомления</param>
public void ShowNotification(string title, string message, NotificationType type)
{
notificationManager.Show(new Notification
{
Message = message,
Expiration = TimeSpan.FromSeconds(3),
Type = type,
Title = title
});
}
/// <summary>
/// Обработчик события нажатия кнопки для выбора изображения и его отображения в Image1.
/// </summary>
/// <param name="sender">Отправитель</param>
/// <param name="e">Аргументы</param>
private async void Button_Click(object? sender, Avalonia.Interactivity.RoutedEventArgs e)
{
try
{
var top = TopLevel.GetTopLevel(this);
var result = await top!.StorageProvider.OpenFilePickerAsync(new FilePickerOpenOptions
{
AllowMultiple = false,
FileTypeFilter = [FilePickerFileTypes.ImageAll],
Title = "Выберите изображение"
});
if (result.Count == 0)
return;
var imagePath = result[0].Path.LocalPath;
string newImageName = $"{Guid.NewGuid()}{Path.GetExtension(imagePath)}";
string newImagePath = Path.Combine("Images", newImageName);
Directory.CreateDirectory("Images");
File.Copy(imagePath, newImagePath);
Image1.Source = new Bitmap(newImagePath);
MainView.Current.ShowNotification("Успех", "Изображение успешно загружено и сохранено.", NotificationType.Success);
}
catch (Exception ex)
{
MainView.Current.ShowNotification("Ошибка", $"Не удалось загрузить изображение: {ex.Message}", NotificationType.Error);
}
}
}
}