Files
ADP/TestingModule/ViewModels/LogAreaViewModel.cs
2026-06-11 15:45:29 +08:00

82 lines
2.4 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using UIShare.GlobalVariable;
using Logger;
using Prism.Mvvm;
using System.Collections.ObjectModel;
using System.Reflection;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Threading;
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; }
public LogAreaViewModel(IContainerProvider containerProvider) : base(containerProvider)
{
ClearLogCommand = new DelegateCommand(ClearLog);
// 2. 保持原有逻辑,但请确保在 Dispose 中对其进行清理
LoggerHelper.Progress = new System.Progress<(string message, string color, int depth)>(
log =>
{
// 增加防御性代码:防止进入销毁流程时异步回调引发空引用异常
if (Logs == null) return;
var brush = (Brush)new BrushConverter().ConvertFromString(log.color);
Logs.Add(new LogItem(log.message, brush, log.depth));
});
}
private void ClearLog()
{
Logs?.Clear();
}
/// <summary>
/// 完善后的资源释放方法
/// </summary>
public void Dispose()
{
try
{
LoggerHelper.Progress = null!;
if (Logs != null)
{
Logs.Clear();
Logs = null!;
}
}
catch (Exception ex)
{
Logger.LoggerHelper.ErrorWithNotify($"释放日志组件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;
}
}
}