WPF Validation Rule Update anyway

房东的猫 提交于 2019-12-13 17:57:47

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/13604856/wpf-validation-rule-update-anyway

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!