我正在尝试针对对象验证 WPF 表单。当我在文本框中输入内容时,验证会触发失去焦点回到文本框,然后擦除我写的任何内容。但是,如果我只是加载 WPF 应用程序并在文本框上制表符而不从文本框中写入和擦除任何内容,那么它不会被触发。
这是 Customer.cs 类:
public class Customer : IDataErrorInfo
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Error
{
get { throw new NotImplementedException(); }
}
public string this[string columnName]
{
get
{
string result = null;
if (columnName.Equals("FirstName"))
{
if (String.IsNullOrEmpty(FirstName))
{
result = "FirstName cannot be null or empty";
}
}
else if (columnName.Equals("LastName"))
{
if (String.IsNullOrEmpty(LastName))
{
result = "LastName cannot be null or empty";
}
}
return result;
}
}
}
这是 WPF 代码:
<TextBlock Grid.Row="1" Margin="10" Grid.Column="0">LastName</TextBlock>
<TextBox Style="{StaticResource textBoxStyle}" Name="txtLastName" Margin="10"
VerticalAlignment="Top" Grid.Row="1" Grid.Column="1">
<Binding Source="{StaticResource CustomerKey}" Path="LastName"
ValidatesOnExceptions="True" ValidatesOnDataErrors="True"
UpdateSourceTrigger="LostFocus"/>
</TextBox>