93 lines
2.8 KiB
C#
93 lines
2.8 KiB
C#
using UIShare.GlobalVariable;
|
||
using Logger;
|
||
using Prism.Ioc;
|
||
using Prism.Mvvm;
|
||
using System;
|
||
using System.Collections.ObjectModel;
|
||
using System.Reflection;
|
||
using System.Windows.Input;
|
||
using System.Windows.Media;
|
||
using UIShare.ViewModelBase;
|
||
|
||
namespace TestingModule.ViewModels
|
||
{
|
||
public class LogAreaViewModel : NavigateViewModelBase, IDisposable
|
||
{
|
||
|
||
|
||
// 日志集合
|
||
private ObservableCollection<LogItem> _logs = new();
|
||
|
||
public ObservableCollection<LogItem> Logs
|
||
{
|
||
get => _logs;
|
||
set => SetProperty(ref _logs, value);
|
||
}
|
||
public ICommand ClearLogCommand { get; set; }
|
||
|
||
private readonly ScopedContext _scopedContext;
|
||
private readonly GlobalInfo _globalInfo;
|
||
private IProgress<(string Message, Brush Color, int Depth)>? _logProgress;
|
||
|
||
public LogAreaViewModel(IContainerProvider containerProvider) : base(containerProvider)
|
||
{
|
||
ClearLogCommand = new DelegateCommand(ClearLog);
|
||
_scopedContext = containerProvider.Resolve<ScopedContext>();
|
||
_globalInfo = containerProvider.Resolve<GlobalInfo>();
|
||
|
||
// 创建本作用域专属的日志接收器并注册到 ScopedContext
|
||
_logProgress = new Progress<(string Message, Brush Color, int Depth)>(log =>
|
||
{
|
||
if (Logs == null) return;
|
||
Logs.Add(new LogItem(log.Message, log.Color, log.Depth));
|
||
});
|
||
_scopedContext.LogProgress = _logProgress;
|
||
}
|
||
|
||
private void ClearLog()
|
||
{
|
||
Logs?.Clear();
|
||
}
|
||
|
||
/// <summary>
|
||
/// 完善后的资源释放方法
|
||
/// </summary>
|
||
public void Dispose()
|
||
{
|
||
try
|
||
{
|
||
// 注销本作用域的日志接收器,避免 Dispose 后仍收到旧消息
|
||
if (_scopedContext != null && _scopedContext.LogProgress == _logProgress)
|
||
{
|
||
_scopedContext.LogProgress = null;
|
||
}
|
||
_logProgress = null;
|
||
|
||
if (Logs != null)
|
||
{
|
||
Logs.Clear();
|
||
Logs = null!;
|
||
}
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
Logger.LoggerHelper.ErrorWithNotify(_scopedContext != null ? _globalInfo.CurrentScope : "", $"释放日志组件(LogAreaViewModel)资源失败: {ex.Message}");
|
||
}
|
||
}
|
||
}
|
||
|
||
// 日志条目类
|
||
public class LogItem
|
||
{
|
||
public string Message { get; set; }
|
||
public Brush Color { get; set; } = Brushes.Black;
|
||
public int Depth { get; set; }
|
||
public LogItem(string message, Brush color, int depth = 0)
|
||
{
|
||
Message = new string(' ', depth * 20) + message;
|
||
Color = color;
|
||
Depth = depth;
|
||
}
|
||
}
|
||
}
|