无论如何,WPF验证规则更新 [英] WPF Validation Rule Update anyway

查看:89
本文介绍了无论如何,WPF验证规则更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的视图上有一个文本框,其中有一个验证规则:

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);
    }
}

输入空字符串时. bound属性未更新,并且文本框"标记为红色.我需要更新源,但仍将标记保留在文本框中. (此输入稍后将由EF再次验证.)

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).

我该怎么办?

推荐答案

您可以通过将验证规则的ValidationStep属性设置为"UpdatedValue"来实现:

You can do this by setting the ValidationStep property of the validation rule to "UpdatedValue":

<Binding.ValidationRules>
    <c:EmptyStringRule ValidationStep="UpdatedValue"/>
</Binding.ValidationRules>

请注意,这会导致将BindingExpression传递给验证规则类,而不是传递给实际字段值,因此您必须相应地修改验证规则,以查询已更新字段的值. (在我的示例中,绑定的字符串属性称为MyViewModel.MyStringProperty):

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);
    }
}

通过此设置,当文本设置为空时,它实际上应该对MyStringProperty进行更新,但仍会进行验证.

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.

这篇关于无论如何,WPF验证规则更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆