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 _logs = new(); public ObservableCollection 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(); } /// /// 完善后的资源释放方法 /// 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; } } }