如您从标题中可以看出,我将要询问一个曾经被问过很多次的问题。但是,在阅读了所有其他类似问题后,我仍然找不到解决我的问题的合适方法。
我有一个带基本验证的模型类:
partial class Player : IDataErrorInfo
{
public bool CanSave { get; set; }
public string this[string columnName]
{
get
{
string result = null;
if (columnName == "Firstname")
{
if (String.IsNullOrWhiteSpace(Firstname))
{
result = "Geef een voornaam in";
}
}
if (columnName == "Lastname")
{
if (String.IsNullOrWhiteSpace(Lastname))
{
result = "Geef een familienaam in";
}
}
if (columnName == "Email")
{
try
{
MailAddress email = new MailAddress(Email);
}
catch (FormatException)
{
result = "Geef een geldig e-mailadres in";
}
}
if (columnName == "Birthdate")
{
if (Birthdate.Value.Date >= DateTime.Now.Date)
{
result = "Geef een geldige geboortedatum in";
}
}
CanSave = true; // this line is wrong
return result;
}
}
public string Error { get { throw new NotImplementedException();} }
}
每次属性更改时(即每当用户在文本框中输入字符时),都会进行此验证:
<TextBox Text="{Binding CurrentPlayer.Firstname, ValidatesOnDataErrors=True, UpdateSourceTrigger=PropertyChanged}" VerticalAlignment="Top" Width="137" IsEnabled="{Binding Editing}" Grid.Row="1"/>
这很完美。验证会发生(绑定的PropertyChanged代码在VM上对CurrentPlayer属性执行,它是Player的一个对象)。
现在我想做的是在验证失败时禁用保存按钮。
首先,最简单的解决方案似乎可以在这个线程中找到:Enable Disable save button during Validation using IDataErrorInfo。
如果我想使用接受的解决方案,我必须编写两次我的验证代码,因为我不能简单地使用索引器。编写双倍的代码绝对不是我想要的,所以这不是我的问题的解决方法。
该线程上的第二个答案起初听起来非常有前途,但问题在于我有多个需要进行验证的字段。这样一来,一切都依赖于最后一个被检查的属性(因此,如果该字段正确填写,则CanSave将为true,即使还存在其他无效字段)。
我发现的另一种解决方案是使用一个ErrorCount属性。但由于我在每个属性更改时进行验证(因此在每次键入字符时进行验证),这也是不可能的 - 我怎么知道何时增加/减少ErrorCount呢?
什么是解决这个问题的最佳方法?
谢谢
if
都变得不必要。但是假设您要使用它们,您正在if(A)
中执行if(B)
,因此您可以改为使用if(A && B)
。如果在if
中只执行一个语句,则无需键入{
和}
字符。通过使用映射,此示例可以缩短到约20行,而不是约50行;将您的开发速度加倍。 - Tamara Wijsman