Files
ConeCalorimeter/ConeCalorimeter/ViewModels/RealtimeDataViewModel.cs
GukSang.Jin d11e1d4270 更新
2026-05-05 18:47:25 +08:00

123 lines
3.5 KiB
C#

using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Windows;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using ConeCalorimeter.Services;
using Microsoft.Win32;
namespace ConeCalorimeter.ViewModels;
public sealed class RealtimeDataViewModel : PageViewModel
{
private readonly Action _closeAction;
private readonly IExperimentDataService _experimentDataService;
private readonly IRealtimeDataExportService _realtimeDataExportService;
private string _statusText = string.Empty;
public RealtimeDataViewModel(
IExperimentDataService experimentDataService,
IRealtimeDataExportService realtimeDataExportService,
Action closeAction) : base("实时数据")
{
_experimentDataService = experimentDataService;
_realtimeDataExportService = realtimeDataExportService;
_closeAction = closeAction;
Rows = [];
CloseCommand = new RelayCommand(_closeAction);
ClearCommand = new RelayCommand(ClearRows);
ExportCommand = new RelayCommand(ExportRows);
RebuildRows();
_experimentDataService.Records.CollectionChanged += RecordsChanged;
}
public ObservableCollection<RealtimeDataRowViewModel> Rows { get; }
public IRelayCommand CloseCommand { get; }
public IRelayCommand ClearCommand { get; }
public IRelayCommand ExportCommand { get; }
public string StatusText
{
get => _statusText;
private set => SetProperty(ref _statusText, value);
}
private void RecordsChanged(object? sender, NotifyCollectionChangedEventArgs e)
{
if (e.Action == NotifyCollectionChangedAction.Add && e.NewItems is not null)
{
foreach (var item in e.NewItems)
{
if (item is ConeCalorimeter.Models.RealtimeDataRecord record)
{
Rows.Add(new RealtimeDataRowViewModel(record));
}
}
StatusText = $"记录数:{Rows.Count}";
return;
}
RebuildRows();
}
private void RebuildRows()
{
Rows.Clear();
foreach (var record in _experimentDataService.Records)
{
Rows.Add(new RealtimeDataRowViewModel(record));
}
StatusText = $"记录数:{Rows.Count}";
}
private void ClearRows()
{
_experimentDataService.ClearRecords();
}
private void ExportRows()
{
var records = _experimentDataService.Records.ToList();
if (records.Count == 0)
{
StatusText = "没有可导出的数据";
return;
}
var dialog = new SaveFileDialog
{
Title = "导出实时数据",
Filter = "Excel 97-2003 工作簿 (*.xls)|*.xls",
FileName = $"实时数据_{DateTime.Now:yyyyMMdd_HHmmss}.xls",
DefaultExt = ".xls",
AddExtension = true,
OverwritePrompt = true
};
if (dialog.ShowDialog() != true)
{
StatusText = "已取消导出";
return;
}
try
{
_realtimeDataExportService.Export(dialog.FileName, records);
StatusText = $"已导出:{dialog.FileName}";
}
catch (Exception ex)
{
StatusText = $"导出失败:{ex.Message}";
MessageBox.Show(StatusText, "导出实时数据", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
}