CommunicationAddVM.cs 1.55 KB
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using HHECS.DAQClient.DataAccess;
using HHECS.DAQClient.Model;
using System.Windows;
using MessageBox = HandyControl.Controls.MessageBox;

namespace HHECS.DAQClient.ViewModel.CommunicationVM
{
    public partial class CommunicationAddVM : ObservableObject
    {
        [ObservableProperty]
        private CommunicationConfig communicationConfig = new CommunicationConfig();

        [ObservableProperty]
        private Dictionary<string, CommunicationTypeConst> communicationTypes = new Dictionary<string, CommunicationTypeConst>();

        public Window Owner { get; set; }

        private readonly DataContext _context;

        public CommunicationAddVM(DataContext context)
        {
            _context = context;
            InitialData();
        }

        private void InitialData()
        {
            CommunicationTypes = Enum.GetNames<CommunicationTypeConst>().ToDictionary(x => x, Enum.Parse<CommunicationTypeConst>);
        }

        [RelayCommand]
        public void Save()
        {
            try
            {
                _context.CommunicationConfigs.Add(CommunicationConfig);
                _context.SaveChanges();
                Owner.DialogResult = true;
                MessageBox.Success("保存成功");
            }
            catch (Exception ex)
            {
                MessageBox.Error($"保存数据失败.{ex.Message}");
            }
        }

        [RelayCommand]
        public void Cancel()
        {
            Owner.Close();
        }
    }
}