Files
home-PC 875e331116 Phase 0: 项目初始化与基础架构
- 创建 .NET 8 WPF 项目 PersonalToolBox
- 引入 NuGet 包: CommunityToolkit.Mvvm, System.Text.Json, Microsoft.Extensions.DependencyInjection
- 建立 MVVM 目录结构: Models/ ViewModels/ Views/ Services/ Helpers/
- 实现 LogEntry 模型 (时间/日志级别/内容)
- 实现 ILogService 接口与 LogService (线程安全, 通过 Dispatcher 推送到 UI)
- 配置 DI 容器 (App.xaml.cs) 注册日志服务和主窗口
- 添加 .gitignore 文件
2026-05-09 20:26:51 +08:00

67 lines
1.5 KiB
C#

using System.Collections.ObjectModel;
using System.Windows;
using PersonalToolBox.Models;
namespace PersonalToolBox.Services;
/// <summary>
/// 日志服务实现,管理底部日志打印栏数据
/// 通过 ObservableCollection 将日志实时推送到 UI
/// </summary>
public class LogService : ILogService
{
public ObservableCollection<LogEntry> Logs { get; } = new();
public void Info(string message)
{
var entry = new LogEntry
{
Timestamp = DateTime.Now,
Level = LogLevel.Info,
Content = message
};
AddLog(entry);
}
public void Warning(string message)
{
var entry = new LogEntry
{
Timestamp = DateTime.Now,
Level = LogLevel.Warning,
Content = message
};
AddLog(entry);
}
public void Error(string message)
{
var entry = new LogEntry
{
Timestamp = DateTime.Now,
Level = LogLevel.Error,
Content = message
};
AddLog(entry);
}
public void Clear()
{
if (Application.Current != null)
Application.Current.Dispatcher.Invoke(() => Logs.Clear());
else
Logs.Clear();
}
/// <summary>
/// 将日志条目安全地添加到 UI 线程的集合中
/// </summary>
private void AddLog(LogEntry entry)
{
if (Application.Current != null)
Application.Current.Dispatcher.Invoke(() => Logs.Add(entry));
else
Logs.Add(entry);
}
}