csharp
public class BaseModel : BindableBase, IDataErrorInfo
{
public Func<object, bool> UniquenessCheck { get; set; }
public string this[string columnName]
{
get
{
PropertyInfo pi = this.GetType().GetProperty(columnName);
var value = pi.GetValue(this, null);
if (pi.IsDefined(typeof(Attrite.RequiredAttribute), true))
{
if (value == null || string.IsNullOrEmpty(value.ToString()))
return pi.GetCustomAttribute<Attrite.RequiredAttribute>().PropName = "不能为空";
}
return string.Empty;
}
}
public string Error => null;
}
csharp
public class UserModel : BaseModel
{
public UserModel() { }
private string _userName;
[Required("不能为空")]
public string UserName
{
get { return _userName; }
set
{
SetProperty(ref _userName, value);
}
}
}
csharp
public class MainWindowViewModel : BindableBase
{
private string _title = "Prism Application";
public string Title
{
get { return _title; }
set { SetProperty(ref _title, value); }
}
private UserModel _user;
public UserModel User
{
get { return _user; }
set { SetProperty(ref _user, value); }
}
public MainWindowViewModel()
{
User = new UserModel();
User.UserName = "";
}
}
csharp
<Grid>
<TextBox x:Name="tb" Text="{Binding User.UserName, Mode=TwoWay, ValidatesOnDataErrors=True}" />
<TextBox Text="{Binding Path=(Validation.Errors)[0].ErrorContent, ElementName=tb}" />
</Grid>