using GalaSoft.MvvmLight; using GalaSoft.MvvmLight.Command; using Microsoft.Extensions.DependencyInjection; using SlnMesnac.Model.domain; using SlnMesnac.Repository.service; using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Documents; namespace SlnMesnac.WPF.ViewModel { public class FormulaWindowViewModel : ObservableObject { private ILogoFormulaService? formulaService; public FormulaWindowViewModel() { formulaService = App.ServiceProvider.GetService(); AddCommand = new RelayCommand(AddRecord); DeleteCommand = new RelayCommand(t => DeleteRecord(t)); LoadDataAsync(); } #region 加载DataGrid数据 private async void LoadDataAsync() { List list = await formulaService.GetListAsync(); if (list == null || list.Count == 0) return; list = list.OrderBy(x => x.Key).ToList(); await App.Current.Dispatcher.BeginInvoke((Action)(() => { LogoFormulaDataGrid.Clear(); foreach (LogoFormula verify in list) { LogoFormulaDataGrid.Add(verify); } })); } #endregion private async void DeleteRecord(int key) { if (key>=0) { List list = await formulaService.GetListAsync(); if (list == null || list.Count == 0) return; LogoFormula formula = list.FirstOrDefault(t => t.Key == key); if (formula != null) { bool result = await formulaService.DeleteAsync(formula); if (result) { MessageBox.Show("删除成功"); LoadDataAsync(); } } } } private async void AddRecord() { string key = KeyTxt; string value = ValueTxt; if(string.IsNullOrEmpty(key) || string.IsNullOrEmpty(value)){ MessageBox.Show("两个值都不能为空"); return; } List list = await formulaService.GetListAsync(); if (list == null || list.Count == 0) return; try { int result = int.Parse(key); Console.WriteLine("转换成功,结果是:" + result); } catch (FormatException) { MessageBox.Show("Key必须为数字"); return; } LogoFormula formula = list.FirstOrDefault(t => t.Key == int.Parse(key)); if (formula != null) { MessageBox.Show("Key已经存在"); return; } else { bool result = await formulaService.InsertAsync(new LogoFormula() { Key = int.Parse(key), Value = value }); if (result) { MessageBox.Show("添加成功"); LoadDataAsync(); } } } #region 属性 /// /// Key /// private string _KeyTxt; public string KeyTxt { get { return _KeyTxt; } set { _KeyTxt = value; RaisePropertyChanged(); } } /// /// Value /// private string _ValueTxt; public string ValueTxt { get { return _ValueTxt; } set { _ValueTxt = value; RaisePropertyChanged(); } } #region 初始化datagrid private ObservableCollection _LogoFormulaDataGrid = new ObservableCollection(); public ObservableCollection LogoFormulaDataGrid { get { return _LogoFormulaDataGrid; } set { _LogoFormulaDataGrid = value; RaisePropertyChanged();//属性通知 } } #endregion #endregion /// /// 查询事件 /// public RelayCommand AddCommand { get; set; } /// /// 更新检测类型事件 /// public RelayCommand DeleteCommand { get; set; } } }