I am unable to get a WPF
ValidationRule
to detect an empty
TextBox
.
My cut-down code is as follows:
public class NonEmptyStringValidator : ValidationRule
{
public override ValidationResult Validate( object value, CultureInfo cultureInfo )
{
ValidationResult validationResult = new ValidationResult( false, "Value cannot be empty." );
if( value != null )
{
string valueAsString = value as string;
if( valueAsString.Length > 0 )
validationResult = ValidationResult.ValidResult;
}
return validationResult;
}
}
My cut-down XAML is as follows:
<TextBox
<TextBox.Text>
<Binding Path="SelectedUser.Username" UpdateSourceTrigger="LostFocus">
<Binding.ValidationRules>
<u:NonEmptyStringValidator/>
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
A breakpoint placed inside the
Validate()
function reveals that the code is not run until there is something in the
TextBox
. Is there a way to get it to work to detect an empty string?
What I have tried:
I have tried various values for
UpdateSourceTrigger
.
I have also tried hooking into the
LostFocus
event for the
TextBox
and writing code to handle this manually. This gets very messy because one thing I need to do is keep focus on the
TextBox
until is has something in it, and calling
Focus()
seems to cause the
LostFocus
event to fire again, which is something else I don't understand.