使用新框架与技术代替旧框架与技术,实现涂装车间后道标签扫码程序
This commit is contained in:
@@ -0,0 +1,86 @@
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
using System.Text;
|
||||
using NLog;
|
||||
using Prism.Events;
|
||||
using Prism.Regions;
|
||||
using RIZO_Application.Core;
|
||||
using RIZO_Application.Core.Mvvm;
|
||||
|
||||
namespace RIZO_Application.Modules.LogModule.ViewModels
|
||||
{
|
||||
public class SystemLogViewModel : RegionViewModelBase
|
||||
{
|
||||
private readonly IEventAggregator _eventAggregator;
|
||||
private SubscriptionToken _token;
|
||||
private readonly StringBuilder _logMessageBuilder = new StringBuilder();
|
||||
private Logger _logger = LogManager.GetCurrentClassLogger();
|
||||
private const int MaxLogLength = 1000; // 假设最大长度为1000,可以根据实际情况调整
|
||||
private const string LogFormat = "\n{0}: {1}";
|
||||
|
||||
// 定义一个日志更新事件
|
||||
public event EventHandler LogUpdated;
|
||||
|
||||
public string LogMessage
|
||||
{
|
||||
get { return _logMessageBuilder.ToString(); }
|
||||
set
|
||||
{
|
||||
_logMessageBuilder.Clear();
|
||||
_logMessageBuilder.Append(value);
|
||||
RaisePropertyChanged(nameof(LogMessage));
|
||||
}
|
||||
}
|
||||
|
||||
public SystemLogViewModel(
|
||||
IRegionManager regionManager,
|
||||
IEventAggregator eventAggregator)
|
||||
: base(regionManager)
|
||||
{
|
||||
OnLogReceived("初始化日志系统");
|
||||
_eventAggregator = eventAggregator;
|
||||
// 订阅事件,使用UI线程处理,保持强引用
|
||||
_token = _eventAggregator.GetEvent<SystemLogEvent>().Subscribe(OnLogReceived, ThreadOption.UIThread, true);
|
||||
}
|
||||
|
||||
private void OnLogReceived(string message)
|
||||
{
|
||||
string newLog = string.Format(LogFormat, DateTime.Now, message);
|
||||
_logMessageBuilder.Append(newLog);
|
||||
|
||||
if (_logMessageBuilder.Length > MaxLogLength)
|
||||
{
|
||||
// 计算需要截取的位置,保留最新的日志
|
||||
int startIndex = Math.Max(0, _logMessageBuilder.Length - MaxLogLength);
|
||||
_logMessageBuilder.Remove(0, startIndex);
|
||||
}
|
||||
|
||||
RaisePropertyChanged(nameof(LogMessage));
|
||||
_logger.Info(newLog);
|
||||
|
||||
// 触发日志更新事件
|
||||
OnLogUpdated();
|
||||
}
|
||||
|
||||
protected virtual void OnLogUpdated()
|
||||
{
|
||||
LogUpdated?.Invoke(this, EventArgs.Empty);
|
||||
}
|
||||
|
||||
public void Destroy()
|
||||
{
|
||||
_token?.Dispose();
|
||||
}
|
||||
|
||||
public void AddTestLogMessage()
|
||||
{
|
||||
// 示例实现,可根据需求修改
|
||||
OnLogReceived("测试日志消息");
|
||||
}
|
||||
|
||||
public override void OnNavigatedTo(NavigationContext navigationContext)
|
||||
{
|
||||
//do something
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user