作图网站,wordpress做大型网站,购物网站项目介绍,网上培训课程平台WPF提供了能与数据绑定系统紧密协作的验证功能。提供了两种方法用于捕获非法值#xff1a;
1、可在数据对象中引发错误。
可以在设置属性时抛出异常#xff0c;通常WPF会忽略所有在设置属性时抛出的异常#xff0c;但可以进行配置#xff0c;从而显示更有帮助的可视化指示…WPF提供了能与数据绑定系统紧密协作的验证功能。提供了两种方法用于捕获非法值
1、可在数据对象中引发错误。
可以在设置属性时抛出异常通常WPF会忽略所有在设置属性时抛出的异常但可以进行配置从而显示更有帮助的可视化指示。另一种选择是在自定义的数据类中实现 INotifyDataErrorInfo 或 IDataErrorInfo 接口从而可得到指示错误的功能而不会抛出异常。
2、可在绑定级别上定义验证。
这种方法可获得使用相同验证的灵活性而不必考虑使用的是哪个控件。更好的是因为是在不同类中定义验证可以很容易的在存储类似数据类型的多个绑定中重用验证。
错误模板
错误模板使用的是装饰层装饰层是位于普通窗口内容之上的绘图层。使用装饰层可添加可视化装饰来指示错误而不用替换控件背后的控件模板或改变窗口的布局。文本框的标准错误模板通过在相应文本框的上面添加红色的Border元素来指示发生了错误。可使用错误模板添加其他细节。
Style TargetType{x:Type TextBox}Setter PropertyValidation.ErrorTemplateSetter.ValueControlTemplateDockPanel LastChildFillTrueTextBlock DockPanel.DockRight ForegroundRed FontSize14 FontWeightBold ToolTip{Binding ElementNameadornerPlaceholder, PathAdornedElement.(Validation.Errors)[0].ErrorContent}*/TextBlockBorder BorderBrushGreen BorderThickness1AdornedElementPlaceholder NameadornerPlaceholder/AdornedElementPlaceholder/Border/DockPanel/ControlTemplate/Setter.Value/SetterStyle.TriggersTrigger PropertyValidation.HasError ValuetrueSetter PropertyToolTip Value{Binding RelativeSource{RelativeSource Self}, Path(Validation.Errors)[0].ErrorContent}//Trigger/Style.Triggers
/Style
在数据对象中引发错误
我这里分别尝试了 IDataErrorInfo 与 INotifyDataErrorInfo 接口这俩需要分别对应使用 DataErrorValidationRule/ 与 NotifyDataErrorValidationRule/ 。
IDataErrorInfo 接口定义了Error字段这个字段在结构有多个字段时难以映射于是在[]下标下实现逻辑。
INotifyDataErrorInfo 接口需要实现 HasErrorGetErrors 两个函数并需要在属性的set 访问器内实现校验逻辑并管理Error信息。
总体来说在数据对象中引发错误不是一个好选择验证逻辑硬编码在数据对象中不利于复用。 在绑定级别上定义验证
在绑定级别上定义验证是针对于数据类型自定义验证规则可以对同一种数据类型进行复用。自定义验证规则需要继承自 ValidationRule 类需要实现 Validate 函数在其中完成自定义验证内容。
public class PriceRule : ValidationRule
{private decimal min 0;private decimal max decimal.MaxValue;public decimal Min{get min;set min value;}public decimal Max{get max;set max value;}public override ValidationResult Validate(object value, CultureInfo cultureInfo){decimal price 0;try{if (((string)value).Length 0){price Decimal.Parse((string)value, NumberStyles.Any, cultureInfo);}}catch{return new ValidationResult(false, Illegal characters.);}if (price min || price max){return new ValidationResult(false, Not in the range Min to Max .);}else{return new ValidationResult(true, null);}}
}
验证多个值
如果需要执行对两个或更多个绑定值的验证可以通过 BindingGroup 来实现将需要校验的多个控件放置于同一个容器中在容器级别应用验证规则需要通过事件主动触发验证通常是子组件失去焦点时。
Grid Grid.Row3 Grid.ColumnSpan2 DataContext{Binding PathPerson} TextBoxBase.LostFocusGrid_LostFocusGrid.ColumnDefinitionsColumnDefinition/ColumnDefinition//Grid.ColumnDefinitionsGrid.RowDefinitionsRowDefinition/RowDefinition//Grid.RowDefinitionsGrid.BindingGroupBindingGroup x:NamepersonValidationBindingGroup.ValidationRuleslocal:PersonRule//BindingGroup.ValidationRules/BindingGroup/Grid.BindingGroupTextBlock Grid.Row0 Grid.Column0Person ID:/TextBlockTextBox Grid.Row0 Grid.Column1 Text{Binding PathID} /TextBlock Grid.Row1 Grid.Column0Person Name:/TextBlockTextBox Grid.Row1 Grid.Column1 Text{Binding PathName}/
/Grid
public class Person : ViewModelBase
{private string name string.Empty;public string Name { getname; set SetProperty(ref name, value); }private string id string.Empty;public string ID { get id; set SetProperty(ref id, value); }
}
public class PersonRule : ValidationRule
{public override ValidationResult Validate(object value, CultureInfo cultureInfo){BindingGroup bindingGroup (BindingGroup)value;Person? person bindingGroup.Items[0] as Person;string name (string)bindingGroup.GetValue(person, Name);string id (string)bindingGroup.GetValue(person, ID);if ((name ) (id )){return new ValidationResult(false, A Person requires a ID or Name.);}else{return new ValidationResult(true, null);}}
}
下面贴出完整的测试代码
MainWindow.xaml
Window x:ClassTestValidation.MainWindowxmlnshttp://schemas.microsoft.com/winfx/2006/xaml/presentationxmlns:xhttp://schemas.microsoft.com/winfx/2006/xamlxmlns:dhttp://schemas.microsoft.com/expression/blend/2008xmlns:mchttp://schemas.openxmlformats.org/markup-compatibility/2006xmlns:localclr-namespace:TestValidationmc:IgnorabledTitleMainWindow Height450 Width800Border Padding7 Margin7 BackgroundLightSteelBlueGrid x:NamemyGridGrid.ResourcesStyle TargetType{x:Type TextBox}Setter PropertyValidation.ErrorTemplateSetter.ValueControlTemplateDockPanel LastChildFillTrueTextBlock DockPanel.DockRight ForegroundRed FontSize14 FontWeightBold ToolTip{Binding ElementNameadornerPlaceholder, PathAdornedElement.(Validation.Errors)[0].ErrorContent}*/TextBlockBorder BorderBrushGreen BorderThickness1AdornedElementPlaceholder NameadornerPlaceholder/AdornedElementPlaceholder/Border/DockPanel/ControlTemplate/Setter.Value/SetterStyle.TriggersTrigger PropertyValidation.HasError ValuetrueSetter PropertyToolTip Value{Binding RelativeSource{RelativeSource Self}, Path(Validation.Errors)[0].ErrorContent}//Trigger/Style.Triggers/Style/Grid.ResourcesGrid.ColumnDefinitionsColumnDefinition WidthAuto/ColumnDefinition//Grid.ColumnDefinitionsGrid.RowDefinitionsRowDefinition Height*/RowDefinition Height*/RowDefinition Height*/RowDefinition Height2*//Grid.RowDefinitionsTextBlock Grid.Row0 Grid.Column0PersonAge:/TextBlockTextBox Grid.Row0 Grid.Column1 DataContext{Binding PathPersonAge}TextBox.TextBinding PathAge NotifyOnValidationErrortrueBinding.ValidationRulesDataErrorValidationRule//Binding.ValidationRules/Binding/TextBox.Text/TextBoxTextBlock Grid.Row1 Grid.Column0PersonName:/TextBlockTextBox Grid.Row1 Grid.Column1 DataContext{Binding PathPersonName}TextBox.TextBinding PathName NotifyOnValidationErrortrueBinding.ValidationRulesNotifyDataErrorValidationRule//Binding.ValidationRules/Binding/TextBox.Text/TextBoxTextBlock Grid.Row2 Grid.Column0PersonPrice:/TextBlockTextBox Grid.Row2 Grid.Column1 DataContext{Binding PathPersonPrice}TextBox.TextBinding PathPrice NotifyOnValidationErrortrueBinding.ValidationRuleslocal:PriceRule Min0//Binding.ValidationRules/Binding/TextBox.Text/TextBoxGrid Grid.Row3 Grid.ColumnSpan2 DataContext{Binding PathPerson} TextBoxBase.LostFocusGrid_LostFocusGrid.ColumnDefinitionsColumnDefinition/ColumnDefinition//Grid.ColumnDefinitionsGrid.RowDefinitionsRowDefinition/RowDefinition//Grid.RowDefinitionsGrid.BindingGroupBindingGroup x:NamepersonValidationBindingGroup.ValidationRuleslocal:PersonRule//BindingGroup.ValidationRules/BindingGroup/Grid.BindingGroupTextBlock Grid.Row0 Grid.Column0Person ID:/TextBlockTextBox Grid.Row0 Grid.Column1 Text{Binding PathID} /TextBlock Grid.Row1 Grid.Column0Person Name:/TextBlockTextBox Grid.Row1 Grid.Column1 Text{Binding PathName}//Grid/Grid/Border
/WindowMainWindow.xaml.cs
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;namespace TestValidation;public class ViewModelBase : INotifyPropertyChanged
{public event PropertyChangedEventHandler? PropertyChanged;protected virtual void OnPropertyChanged([CallerMemberName] string? propertyName null){PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));}protected virtual bool SetPropertyT(ref T member, T value, [CallerMemberName] string? propertyName null){if (EqualityComparerT.Default.Equals(member, value)){return false;}member value;OnPropertyChanged(propertyName);return true;}
}
public class PersonAge : ViewModelBase, IDataErrorInfo
{public string this[string columnName]{get{if(columnName Age){if(Age 0 || Age 150){return Age must not be less than 0 or greater than 150.;}}return null;}}private int age;public int Age { get age; set SetProperty(ref age, value); }public string Error null;
}
public class PersonName : ViewModelBase, INotifyDataErrorInfo
{private string name string.Empty;public string Name {get name;set{bool valid true;foreach (char c in value){if (!char.IsLetterOrDigit(c)){valid false;break;}}if(!valid){Liststring errors new Liststring ();errors.Add(The Name can only contain letters and numbers.);SetErrors(Name, errors);}else{ClearErrors(Name);}SetProperty(ref name, value);}}private Dictionarystring, Liststring errors new Dictionarystring, Liststring();private void SetErrors(string propertyName, Liststring propertyErrors){errors.Remove(propertyName);errors.Add(propertyName, propertyErrors);if (ErrorsChanged ! null)ErrorsChanged(this, new DataErrorsChangedEventArgs(propertyName));}private void ClearErrors(string propertyName){errors.Remove(propertyName);if(ErrorsChanged ! null)ErrorsChanged(this, new DataErrorsChangedEventArgs(propertyName));}public bool HasErrors{get { return errors.Count 0; }}public event EventHandlerDataErrorsChangedEventArgs? ErrorsChanged;public IEnumerable GetErrors(string? propertyName){if(!string.IsNullOrEmpty(propertyName) errors.ContainsKey(propertyName)){return errors[propertyName];}return new Liststring();}
}
public class PersonPrice : ViewModelBase, INotifyPropertyChanged
{private decimal price 0;public decimal Price{get price; set{SetProperty(ref price, value);}}
}public class PriceRule : ValidationRule
{private decimal min 0;private decimal max decimal.MaxValue;public decimal Min{get min;set min value;}public decimal Max{get max;set max value;}public override ValidationResult Validate(object value, CultureInfo cultureInfo){decimal price 0;try{if (((string)value).Length 0){price Decimal.Parse((string)value, NumberStyles.Any, cultureInfo);}}catch{return new ValidationResult(false, Illegal characters.);}if (price min || price max){return new ValidationResult(false, Not in the range Min to Max .);}else{return new ValidationResult(true, null);}}
}public class Person : ViewModelBase
{private string name string.Empty;public string Name { getname; set SetProperty(ref name, value); }private string id string.Empty;public string ID { get id; set SetProperty(ref id, value); }
}
public class PersonRule : ValidationRule
{public override ValidationResult Validate(object value, CultureInfo cultureInfo){BindingGroup bindingGroup (BindingGroup)value;Person? person bindingGroup.Items[0] as Person;string name (string)bindingGroup.GetValue(person, Name);string id (string)bindingGroup.GetValue(person, ID);if ((name ) (id )){return new ValidationResult(false, A Person requires a ID or Name.);}else{return new ValidationResult(true, null);}}
}
public partial class MainWindow : Window
{public MainWindow(){InitializeComponent();myGrid.DataContext this;}public PersonAge PersonAge { get; set; } new PersonAge();public PersonName PersonName { get; set; } new PersonName();public PersonPrice PersonPrice { get; set; } new PersonPrice();public Person Person { get; set; } new Person();private void Grid_LostFocus(object sender, RoutedEventArgs e){personValidation.CommitEdit();}
} 文章转载自: http://www.morning.spfq.cn.gov.cn.spfq.cn http://www.morning.lbqt.cn.gov.cn.lbqt.cn http://www.morning.txlxr.cn.gov.cn.txlxr.cn http://www.morning.nwljj.cn.gov.cn.nwljj.cn http://www.morning.ylmxs.cn.gov.cn.ylmxs.cn http://www.morning.dsgdt.cn.gov.cn.dsgdt.cn http://www.morning.pqbkk.cn.gov.cn.pqbkk.cn http://www.morning.tfwr.cn.gov.cn.tfwr.cn http://www.morning.wsnbg.cn.gov.cn.wsnbg.cn http://www.morning.stmkm.cn.gov.cn.stmkm.cn http://www.morning.sblgt.cn.gov.cn.sblgt.cn http://www.morning.glbnc.cn.gov.cn.glbnc.cn http://www.morning.jpmcb.cn.gov.cn.jpmcb.cn http://www.morning.wqbrg.cn.gov.cn.wqbrg.cn http://www.morning.rdxnt.cn.gov.cn.rdxnt.cn http://www.morning.lwyqd.cn.gov.cn.lwyqd.cn http://www.morning.mflqd.cn.gov.cn.mflqd.cn http://www.morning.mcpdn.cn.gov.cn.mcpdn.cn http://www.morning.ljdhj.cn.gov.cn.ljdhj.cn http://www.morning.thrtt.cn.gov.cn.thrtt.cn http://www.morning.qkrqt.cn.gov.cn.qkrqt.cn http://www.morning.cbqqz.cn.gov.cn.cbqqz.cn http://www.morning.kxypt.cn.gov.cn.kxypt.cn http://www.morning.qxjck.cn.gov.cn.qxjck.cn http://www.morning.jfcbs.cn.gov.cn.jfcbs.cn http://www.morning.kgqww.cn.gov.cn.kgqww.cn http://www.morning.nfnxp.cn.gov.cn.nfnxp.cn http://www.morning.mypxm.com.gov.cn.mypxm.com http://www.morning.wnbqy.cn.gov.cn.wnbqy.cn http://www.morning.nlnmy.cn.gov.cn.nlnmy.cn http://www.morning.zdmrf.cn.gov.cn.zdmrf.cn http://www.morning.nfmtl.cn.gov.cn.nfmtl.cn http://www.morning.wpkr.cn.gov.cn.wpkr.cn http://www.morning.zpkfb.cn.gov.cn.zpkfb.cn http://www.morning.pqcrz.cn.gov.cn.pqcrz.cn http://www.morning.ljygq.cn.gov.cn.ljygq.cn http://www.morning.lbbyx.cn.gov.cn.lbbyx.cn http://www.morning.rqqkc.cn.gov.cn.rqqkc.cn http://www.morning.okiner.com.gov.cn.okiner.com http://www.morning.grwgw.cn.gov.cn.grwgw.cn http://www.morning.mzgq.cn.gov.cn.mzgq.cn http://www.morning.wbysj.cn.gov.cn.wbysj.cn http://www.morning.wncb.cn.gov.cn.wncb.cn http://www.morning.hrnrx.cn.gov.cn.hrnrx.cn http://www.morning.fsjcn.cn.gov.cn.fsjcn.cn http://www.morning.jtwck.cn.gov.cn.jtwck.cn http://www.morning.jtszm.cn.gov.cn.jtszm.cn http://www.morning.lkbyj.cn.gov.cn.lkbyj.cn http://www.morning.fhntj.cn.gov.cn.fhntj.cn http://www.morning.ftmzy.cn.gov.cn.ftmzy.cn http://www.morning.sxjmz.cn.gov.cn.sxjmz.cn http://www.morning.wnnts.cn.gov.cn.wnnts.cn http://www.morning.lwmzp.cn.gov.cn.lwmzp.cn http://www.morning.ghcfx.cn.gov.cn.ghcfx.cn http://www.morning.bktzr.cn.gov.cn.bktzr.cn http://www.morning.tqpnf.cn.gov.cn.tqpnf.cn http://www.morning.kmcfw.cn.gov.cn.kmcfw.cn http://www.morning.rmpkn.cn.gov.cn.rmpkn.cn http://www.morning.tpkxs.cn.gov.cn.tpkxs.cn http://www.morning.dyhlm.cn.gov.cn.dyhlm.cn http://www.morning.rmdwp.cn.gov.cn.rmdwp.cn http://www.morning.llyqm.cn.gov.cn.llyqm.cn http://www.morning.dpfr.cn.gov.cn.dpfr.cn http://www.morning.qsfys.cn.gov.cn.qsfys.cn http://www.morning.lczxm.cn.gov.cn.lczxm.cn http://www.morning.ndynz.cn.gov.cn.ndynz.cn http://www.morning.lqrpk.cn.gov.cn.lqrpk.cn http://www.morning.jqhrk.cn.gov.cn.jqhrk.cn http://www.morning.pdgqf.cn.gov.cn.pdgqf.cn http://www.morning.nzmqn.cn.gov.cn.nzmqn.cn http://www.morning.qqpg.cn.gov.cn.qqpg.cn http://www.morning.dbylp.cn.gov.cn.dbylp.cn http://www.morning.osshjj.cn.gov.cn.osshjj.cn http://www.morning.bqdpy.cn.gov.cn.bqdpy.cn http://www.morning.dqxnd.cn.gov.cn.dqxnd.cn http://www.morning.ftwlay.cn.gov.cn.ftwlay.cn http://www.morning.rsqpc.cn.gov.cn.rsqpc.cn http://www.morning.zqxhn.cn.gov.cn.zqxhn.cn http://www.morning.mrxqd.cn.gov.cn.mrxqd.cn http://www.morning.kpxnz.cn.gov.cn.kpxnz.cn