using SWRIS.Dtos; using SWRIS.Extensions; using System.Collections.ObjectModel; using System.ComponentModel; using System.Linq; using System.Windows; namespace SWRIS.Models.ViewModel { public class RealTimeViewModel : INotifyPropertyChanged { private TrolleyActiveModel activedTrolly; private ObservableCollection records; private ObservableCollection messages; private ObservableCollection trolleys; private ObservableCollection equipments; public RealTimeViewModel(ObservableCollection records) { Equipments = App.DataCenter.Equipments.ConvertToObservableCollection(); Messages = App.DataCenter.Messages; Records = records; Trolleys = App.Config.Trolleys.Select(x => new TrolleyActiveModel { Id = x.Id, Name = x.Name, IsActived = false }).ConvertToObservableCollection(); if (Trolleys.Any()) { Trolleys[0].IsActived = true; ActivedTrolly = Trolleys[0]; } } public ObservableCollection Records { get => records; set { if (records != value) { records = value; OnPropertyChanged(nameof(Records)); } } } public ObservableCollection Messages { get => messages; set { if (messages != value) { messages = value; OnPropertyChanged(nameof(Messages)); } } } public TrolleyActiveModel ActivedTrolly { get => activedTrolly; set { if (activedTrolly != value) { // 取消旧的选中项 if (activedTrolly != null) activedTrolly.IsActived = false; activedTrolly = value; // 激活新的选中项 if (activedTrolly != null) activedTrolly.IsActived = true; OnPropertyChanged(nameof(ActivedTrolly)); } } } public ObservableCollection Trolleys { get => trolleys; set { trolleys = value; OnPropertyChanged(nameof(Trolleys)); } } public ObservableCollection Equipments { get => equipments; set { equipments = value; OnPropertyChanged(nameof(Equipments)); } } public void AddRecord(SimpleRecordDto record) { record.IsNew = true; SafeCollectionInsert(Records, 0, record); // 延迟重置 IsNew 状态,避免重复触发动画 var timer = new System.Windows.Threading.DispatcherTimer { Interval = System.TimeSpan.FromSeconds(3) }; timer.Tick += (s, e) => { record.IsNew = false; timer.Stop(); }; timer.Start(); } protected void SafeCollectionInsert(ObservableCollection collection, int index, T item) { if (Application.Current.Dispatcher.CheckAccess()) { collection.Insert(index, item); } else { Application.Current.Dispatcher.Invoke(() => collection.Insert(index, item)); } } public event PropertyChangedEventHandler PropertyChanged; protected internal virtual void OnPropertyChanged(string propertyName) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } }