using CommunityToolkit.Mvvm.ComponentModel; using CommunityToolkit.Mvvm.Input; using PLCIOPointTool.Services; namespace PLCIOPointTool.ViewModels; public partial class StatusBarViewModel : ObservableObject, IDisposable { private readonly ICommunicator _communicator; private bool disposedValue; [ObservableProperty] private string _netID; [ObservableProperty] private int _port; [ObservableProperty] private bool _isInputEnable; [ObservableProperty] private string _buttonContent; [ObservableProperty] [NotifyCanExecuteChangedFor(nameof(ConnectOrDisconnectCommand))] private bool _isNotInOperating; [ObservableProperty] private string _status; public StatusBarViewModel(ICommunicator communicator) { _netID = string.Empty; _port = 531; _isInputEnable = true; _buttonContent = "Connect"; _isNotInOperating = true; _status = "Disconnected"; _communicator = communicator; _communicator.ConnectionStatusChanged += OnConnectionStatusChanged; } [RelayCommand(CanExecute = nameof(IsNotInOperating))] private void ConnectOrDisconnect() { IsNotInOperating = false; Task.Run(() => { switch (ButtonContent) { case "Connect": _communicator.Open(NetID, Port); break; case "DisConnect": _communicator.Close(); break; default: break; } App.Current.Dispatcher.BeginInvoke(() => { IsNotInOperating = true; }); }); } private void OnConnectionStatusChanged(object? sender, bool e) { App.Current.Dispatcher.Invoke(() => { ButtonContent = e ? "Disconnect" : "Connect"; IsInputEnable = !e; Status = e ? "Connected" : "Disconnected"; }); } protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { // TODO: dispose managed state (managed objects) _communicator.ConnectionStatusChanged -= OnConnectionStatusChanged; } // TODO: free unmanaged resources (unmanaged objects) and override finalizer // TODO: set large fields to null disposedValue = true; } } // // TODO: override finalizer only if 'Dispose(bool disposing)' has code to free unmanaged resources // ~StatusBarViewModel() // { // // Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method // Dispose(disposing: false); // } public void Dispose() { // Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method Dispose(disposing: true); GC.SuppressFinalize(this); } }