我有一个ViewModel
我在其中包含几个属性这样一个WPF的验证检查,如果属性有效
public class ExecutionsCreateViewModel : ValidationViewModelBase
{
[Required(ErrorMessage = "Execution name is required.")]
[StringLength(60, ErrorMessage = "Execution name is too long.")]
public string ExecutionName { get; set; }
[...]
}
那我ValidationViewModelBase
类
public abstract class ValidationViewModelBase : IDataErrorInfo
{
string IDataErrorInfo.Error
{
get
{
throw new NotSupportedException("IDataErrorInfo.Error is not supported.");
}
}
string IDataErrorInfo.this[string propertyName]
{
get
{
if (string.IsNullOrEmpty(propertyName))
{
throw new ArgumentException("Invalid property name", propertyName);
}
string error = string.Empty;
var value = GetValue(propertyName);
var results = new List<ValidationResult>(1);
var result = Validator.TryValidateProperty(
value,
new ValidationContext(this, null, null)
{
MemberName = propertyName
},
results);
if (!result)
{
var validationResult = results.First();
error = validationResult.ErrorMessage;
}
return error;
}
}
private object GetValue(string propertyName)
{
PropertyInfo propInfo = GetType().GetProperty(propertyName);
return propInfo.GetValue(this);
}
}
C#WPF应用程序,这是我的XAML中的TextBox
<TextBox Text="{Binding ExecutionName, UpdateSourceTrigger=PropertyChanged, NotifyOnValidationError=True, ValidatesOnExceptions=True, ValidatesOnDataErrors=True}"/>
属性正在工作,UI正确当财产失效时通知我们(“无效”VisualState
被触发)。
问题是,我不知道如何检查Create方法,如果某些属性当前有效或没有。
private void Create()
{
if(/*check if property is invalid*/)
{
MessageBox.Show(/*property ErrorMessage*/);
return;
}
//Do something with valid properties
}}
我试着Validator.ValidateProperty
(1,2,3),但它不工作和/或它的太乱了。我也在做技巧,如
try
{
ExecutionName = ExecutionName;
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
return;
}
但它在某些情况下不工作,并不看起来很专业。 也许ValidateProperty
是关键,但在许多“教程”后,我仍然不知道如何填充它以满足我的需求。
还有第二个小东西。属性总是验证其属性,所以当用户收到新鲜的表格时ExecutionName
将始终为空,因此Required
属性会将其标记为无效,以便控件将自动变为红色。有没有办法在初始化时跳过验证?
*“有没有办法跳过在初始化验证” * - 是的,初始化不能用来验证任何东西,例如通过直接设置后场值。属性对于用户界面和用户验证来说很好,但不是您的视图模型或属性正在实现通知。 – Sinatr
当我将属性绑定到XML对象属性时,该属性在初始化时会自动调用,因为对象属性会为其自身寻找初始值。将'Mode'设置为'OneWayToSource'没有帮助。当“ValidatesOnDataErrors”设置为true时,即使在初始化时也会检查验证 – Erexo