detect/detect.gui/VWMS/ViewModelBase.cs

80 lines
2.4 KiB
C#
Raw Normal View History

2024-11-26 11:24:25 +08:00
using System;
using Avalonia.Controls.Notifications;
using Avalonia.Threading;
using detect.gui.VWS;
using ReactiveUI;
2024-11-27 15:20:42 +08:00
using Splat;
2024-11-26 11:24:25 +08:00
namespace detect.gui.VWMS;
public class ViewModelBase<T> : ReactiveObject where T : new()
{
private static T? _instance;
public static T Instance()
{
return _instance ??= new T();
}
private bool _isLoading;
public bool IsLoading
{
get => _isLoading;
set => this.RaiseAndSetIfChanged(ref _isLoading, value);
}
private MessageItem? _message;
2024-11-26 15:44:31 +08:00
public MessageItem? Message
2024-11-26 11:24:25 +08:00
{
get => _message;
set => this.RaiseAndSetIfChanged(ref _message, value);
}
protected ViewModelBase()
{
this.WhenAnyValue(x => x.Message).Subscribe(m =>
{
if (m == null) return;
2024-11-27 15:20:42 +08:00
Dispatcher.UIThread.InvokeAsync(() =>
2024-11-26 11:24:25 +08:00
{
2024-11-27 15:20:42 +08:00
Locator.Current.GetService<NotificationWindow>()!.IsSuccess = m.NotificationType == NotificationType.Success;
Locator.Current.GetService<NotificationWindow>()!.IsError = m.NotificationType == NotificationType.Error;
Locator.Current.GetService<NotificationWindow>()!.IsInformation = m.NotificationType == NotificationType.Information;
Locator.Current.GetService<NotificationWindow>()!.IsWarning = m.NotificationType == NotificationType.Warning;
Locator.Current.GetService<NotificationWindow>()!.Message = m.Text;
Locator.Current.GetService<NotificationWindow>()!.Show();
var timer = new DispatcherTimer
2024-11-26 11:24:25 +08:00
{
2024-11-27 15:20:42 +08:00
Interval = TimeSpan.FromSeconds(5)
2024-11-26 11:24:25 +08:00
};
2024-11-27 15:20:42 +08:00
timer.Tick += (s, e) => Locator.Current.GetService<NotificationWindow>()!.Hide();
timer.Start();
2024-11-26 11:24:25 +08:00
});
});
}
}
public class MessageItem : ReactiveObject
{
private readonly string? _text;
public string? Text
{
get => _text;
init => this.RaiseAndSetIfChanged(ref _text, value);
}
private readonly NotificationType _notificationType;
public NotificationType NotificationType
{
get => _notificationType;
init => this.RaiseAndSetIfChanged(ref _notificationType, value);
}
public MessageItem(string? text, NotificationType notificationType)
{
_text = text;
_notificationType = notificationType;
}
}