码迷,mamicode.com
首页 > Windows程序 > 详细

WPF:解决数据验证ValidationRule与按钮Canexcute联动的问题

时间:2020-07-28 16:58:19      阅读:108      评论:0      收藏:0      [点我收藏+]

标签:ready   new   this   tin   方法   value   set   并且   按钮   

想法是这样的,
如果用户输入有误,界面上显示ValidationRule的提示,并且按钮enabled=false(canExcute=fales)
按钮是在输入信息属性改变时刷新Canexcute方法

实际中validRule:RequiredNumberValidRule ValidatesOnTargetUpdated="True"默认是先验证再赋值,如果验证不通过就不赋值,
这就造成了如果验证不通过不能执行Canexcute而按钮无法enabled=false

此时需要更改ValidationRule的属性,设置ValidationStep="UpdatedValue"或者CommiteVALUE

此时还是不行,设置ValidationStep="UpdatedValue后,绑定的属性就变成了绑定的表达式了,
参考:https://stackoverflow.com/questions/10342715/validationrule-with-validationstep-updatedvalue-is-called-with-bindingexpressi
改写了下代码,成功!

····

 <TextBox  Grid.Column="2" Height="26"  >
                    <Binding Path="Compare_Correlation" UpdateSourceTrigger="PropertyChanged">
                        <Binding.ValidationRules>
                            <validRule:RequiredNumberValidRule ValidatesOnTargetUpdated="True" ValidationStep="UpdatedValue" />
                        </Binding.ValidationRules>
                    </Binding>
                </TextBox>


public class RequiredNumberValidRule : ValidationRule
   {
    public override ValidationResult Validate(object value, CultureInfo cultureInfo)
    {
        if (GetBoundValue(value) is null)
        {
            return new ValidationResult(false, "required field.");
        }
        var temp = GetBoundValue(value).ToString();
        double doubleValue;
        if (double.TryParse(temp, out doubleValue))
        {
            return new ValidationResult(true, null);
        }
        else
        {
            return new ValidationResult(false, "Incorrect number format.");
        }
    }

    private object GetBoundValue(object value)
    {
        if (value is BindingExpression)
        {
            // ValidationStep was UpdatedValue or CommittedValue (Validate after setting)
            // Need to pull the value out of the BindingExpression.
            BindingExpression binding = (BindingExpression)value;

            // Get the bound object and name of the property
            object dataItem = binding.DataItem;
            string propertyName = binding.ParentBinding.Path.Path;

            // Extract the value of the property.
            object propertyValue = dataItem.GetType().GetProperty(propertyName).GetValue(dataItem, null);

            // This is what we want.
            return propertyValue;
        }
        else
        {
            // ValidationStep was RawProposedValue or ConvertedProposedValue
            // The argument is already what we want!
            return value;
        }
    }
}

····

WPF:解决数据验证ValidationRule与按钮Canexcute联动的问题

标签:ready   new   this   tin   方法   value   set   并且   按钮   

原文地址:https://www.cnblogs.com/swobble/p/13391448.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!