阅读 189

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

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

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

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

此时还是不行,设置ValidationStep="UpdatedValue后,绑定的属性就变成了绑定的表达式了,
参考:
改写了下代码,成功!

····

 
                    
                        
                            
                        
                    
                


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

····

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

文章分类
代码人生
版权声明:本站是系统测试站点,无实际运营。本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 XXXXXXo@163.com 举报,一经查实,本站将立刻删除。
相关推荐