You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

94 lines
2.9 KiB

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Runtime.CompilerServices;
namespace IOTContainer.MvvmBase
{
/// <summary>
/// ViewModel基础类
/// </summary>
public class ViewModelBase : INotifyPropertyChanged, IDataErrorInfo
{
#region 通知事件
/// <summary>
/// 特性改变事件
/// </summary>
public event PropertyChangedEventHandler PropertyChanged;
/// <summary>
/// 特性改变通知
/// </summary>
/// <param name="propertyName">属性名,若为空则自动获取字段名</param>
protected virtual void RaisePropertyChanged([CallerMemberName] string propertyName = null)
{
this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
/// <summary>
/// 更改属性 并通知特性改变
/// </summary>
/// <typeparam name="T">属性类型</typeparam>
/// <param name="member">属性</param>
/// <param name="value">改变值</param>
/// <param name="propertyName">属性名,若为空则自动获取字段名</param>
protected void SetProperty<T>(ref T member, T value, [CallerMemberName] string propertyName = null)
{
if (!object.Equals(member, value))
{
member = value;
this.RaisePropertyChanged(propertyName);
}
}
#endregion
#region 数据验证
/// <summary>
/// 验证完整性错误
/// </summary>
public string Error
{
get
{
var resultes = new List<ValidationResult>();
var context = new ValidationContext(this);
if (!Validator.TryValidateObject(this, context, resultes, true) && resultes.Count > 0)
{
return string.Join(Environment.NewLine, resultes.Select(r => r.ErrorMessage).ToArray());
}
return string.Empty;
}
}
/// <summary>
/// 验证具体字段错误
/// </summary>
/// <param name="columnName"></param>
/// <returns></returns>
public string this[string columnName]
{
get
{
var resultes = new List<ValidationResult>();
var context = new ValidationContext(this);
context.MemberName = columnName;
var value = this.GetType().GetProperty(columnName).GetValue(this, null);
if (!Validator.TryValidateProperty(value, context, resultes) && resultes.Count > 0)
{
return string.Join(Environment.NewLine, resultes.Select(r => r.ErrorMessage).ToArray());
}
return string.Empty;
}
}
#endregion
}
}