detect/detect.gui/VWMS/ViewModelBase.cs
2024-11-26 11:24:25 +08:00

78 lines
2.0 KiB
C#

using System;
using Avalonia.Controls.Notifications;
using Avalonia.Threading;
using detect.gui.Classes;
using detect.gui.ViewModels;
using detect.gui.VWS;
using ReactiveUI;
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;
protected MessageItem? Message
{
get => _message;
set => this.RaiseAndSetIfChanged(ref _message, value);
}
protected ViewModelBase()
{
this.WhenAnyValue(x => x.Message).Subscribe(m =>
{
if (m == null) return;
Dispatcher.UIThread.Invoke(() =>
{
var title = m.NotificationType switch
{
NotificationType.Error => "错误信息",
NotificationType.Success => "成功信息",
NotificationType.Information => "提示信息",
NotificationType.Warning => "警告信息",
_ => ""
};
NotificationService.Show(title, m.Text, m.NotificationType);
});
});
}
}
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;
}
}