Reputation: 1532
I have a TextBox on my View, that has a Validation Rule:
public class EmptyStringRule : ValidationRule
{
public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
{
if(String.IsNullOrEmpty(value.ToString()))
return new ValidationResult(true,"String Cannot be empty");
return new ValidationResult(true,null);
}
}
When an empty string is entered. the bound property is not updated and the Textbox is marked red. I need to update the Source but still keep the Marker around the Textbox. (The Input is later Validated Again by EF).
How can i do so?
Upvotes: 3
Views: 2061
Reputation: 2368
You can do this by setting the ValidationStep property of the validation rule to "UpdatedValue":
<Binding.ValidationRules>
<c:EmptyStringRule ValidationStep="UpdatedValue"/>
</Binding.ValidationRules>
Note that this causes a BindingExpression to be passed to the validation rule class rather than the actual field value, so you'll have to modify your validation rule accordingly, to query the value of the updated field. (In my example the bound string property is called MyViewModel.MyStringProperty):
public class EmptyStringRule : ValidationRule
{
public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
{
var be = value as BindingExpression;
if (be != null)
{
var item = be.DataItem as MyViewModel;
if (item != null)
{
if (String.IsNullOrEmpty(item.MyStringProperty))
{
return new ValidationResult(false, "String Cannot be empty");
}
}
}
return new ValidationResult(true, null);
}
}
With this set up it should actually do the update to MyStringProperty when the text is set to empty, but will still do a validation.
Upvotes: 8