WPF数据验证(3)——自定义验证规则

来源:互联网 发布:婴幼儿棉裤淘宝 编辑:程序博客网 时间:2024/05/29 18:24

应用自定义验证规则的方法和应用自定义转换器的方法类似。该方法定义了一个 ValidationRule 的类,并且为了执行验证重写 Validate 方法。

public class PositivePriceRule : ValidationRule{        public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo){            decimal price = 0;            decimal maxPrice = Decimal.MaxValue;            if (decimal.TryParse(value.ToString(), out price)){                if (price >= 0 && price < maxPrice){                    return new ValidationResult(true, null);                }            }            return new ValidationResult(false, "UnitCost cannot be negetive");        }    }

再看Product类

 public class Product : INotifyPropertyChanged{        public event PropertyChangedEventHandler PropertyChanged;        private void RaisePropertyChanged(string propertyName){            if (PropertyChanged != null){                this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));            }        }        private decimal unitCost;        public decimal UnitCost{            get { return unitCost; }            set{                unitCost = value;                this.RaisePropertyChanged("UnitCost");            }        }    }

xaml:

<Window x:Class="ValidationRuleDemo.MainWindow"        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"        xmlns:local="clr-namespace:ValidationRuleDemo"        Title="Validation" Height="176" Width="380">    <Window.DataContext>        <local:Product/>    </Window.DataContext>    <StackPanel>        <TextBox Margin="5">            <TextBox.Text>                <Binding Path="UnitCost" Mode="TwoWay" UpdateSourceTrigger="PropertyChanged">                    <Binding.ValidationRules>                        <local:PositivePriceRule/>                    </Binding.ValidationRules>                </Binding>            </TextBox.Text>        </TextBox>    </StackPanel></Window>

Bindding.ValidationRules 集合可包含任何数量的验证规则。将值提交时,WPF将按顺序检查每个验证规则。


当使用PositivePriceRule 验证规则执行验证时,其行为和使用 ExceptionValidationRule验证规则的行为相同——文本框使用黑色轮廓 ,设置HasError 和 Error 属性,并引发 Error 事件。给用户提供一些更有意义的帮助,需要添加一些代码或自己定义 ErrorTemplate 模板。