using System; using System.Collections.Generic; using System.Linq; namespace WalkingTec.Mvvm.Core { /// /// 模型状态接口 /// public interface IModelStateService { /// /// 索引 /// /// /// List this[string name] { get; } /// /// 添加模型错误 /// /// 字段名称 /// 错误信息 void AddModelError(string key, string errorMessage); void RemoveModelError(string key); int Count { get; } IEnumerable Keys { get; } void Clear(); string GetFirstError(); bool IsValid { get; } } /// /// 记录错误的简单类 /// public class MsdError { public string ErrorMessage { get; set; } public Exception Exception { get; set; } } public class BasicMSD : IModelStateService { private Dictionary _states; public BasicMSD() { this._states = new Dictionary(); } public List this[string name] { get { return _states.Where(x => x.Key == name).Select(x => new MsdError { ErrorMessage = x.Value }).ToList(); } } /// /// 添加错误信息 /// /// 错误的字段名 /// 错误信息 public void AddModelError(string key, string errorMessage) { _states.Add(key, errorMessage); } public void RemoveModelError(string key) { _states.Remove(key); } public void Clear() { _states.Clear(); } public string GetFirstError() { string rv = ""; foreach (var key in Keys) { if (this[key].Count > 0) { rv = this[key].First().ErrorMessage; } } return rv; } public int Count => _states.Count; public IEnumerable Keys => _states.Keys; bool IModelStateService.IsValid => _states.Count > 0 ? false : true; } }