我对WPF验证系统非常失望.无论如何!如何通过点击“按钮”验证完整的表单?
由于某些原因WPF中的一切都很复杂!我可以在ASP.NET中的一行代码中进行验证,这需要像WPF中的10-20行代码!
我可以使用我自己的ValidationEngine框架:
Customer customer = new Customer(); customer.FirstName = "John"; customer.LastName = String.Empty; ValidationEngine.Validate(customer); if (customer.brokenRules.Count > 0) { // do something display the broken rules! }
解决方法
如果输入的数据无效,WPF应用程序应禁用按钮提交表单.您可以通过在业务对象上实现
IDataErrorInfo接口来实现这一点,使用带有
ValidatesOnDataErrors
= true的绑定.要在出现错误的情况下自定义单个控件的外观,请设置
Validation.ErrorTemplate
.
XAML:
<Window x:Class="Example.CustomerWindow" ...> <Window.CommandBindings> <CommandBinding Command="ApplicationCommands.Save" CanExecute="SaveCanExecute" Executed="SaveExecuted" /> </Window.CommandBindings> <StackPanel> <TextBox Text="{Binding FirstName,ValidatesOnDataErrors=true,UpdateSourceTrigger=PropertyChanged}" /> <TextBox Text="{Binding LastName,UpdateSourceTrigger=PropertyChanged}" /> <Button Command="ApplicationCommands.Save" IsDefault="True">Save</Button> <TextBlock Text="{Binding Error}"/> </StackPanel> </Window>
这将创建一个带有两个TextBox的窗口,您可以在其中编辑客户的姓氏和姓氏.仅当没有发生验证错误时,才会启用“保存”按钮.按钮下面的TextBlock显示当前的错误,因此用户知道什么.
默认的ErrorTemplate是错误控件周围的一个薄的红色边框.如果这不符合你的视觉概念,看一下关于CodeProject的Validation in Windows Presentation Foundation文章,深入研究一下可以做的事情.
为了使窗口实际工作,窗口和客户端必须有一些基础设施.
代码背后
// The CustomerWindow class receives the Customer to display // and manages the Save command public class CustomerWindow : Window { private Customer CurrentCustomer; public CustomerWindow(Customer c) { // store the customer for the bindings DataContext = CurrentCustomer = c; InitializeComponent(); } private void SaveCanExecute(object sender,CanExecuteRoutedEventArgs e) { e.CanExecute = ValidationEngine.Validate(CurrentCustomer); } private void SaveExecuted(object sender,ExecutedRoutedEventArgs e) { CurrentCustomer.Save(); } } public class Customer : IDataErrorInfo,INotifyPropertyChanged { // holds the actual value of FirstName private string FirstNamebackingStore; // the accessor for FirstName. Only accepts valid values. public string FirstName { get { return FirstNamebackingStore; } set { FirstNamebackingStore = value; ValidationEngine.Validate(this); OnPropertyChanged("FirstName"); } } // similar for LastName string IDataErrorInfo.Error { get { return String.Join("\n",brokenRules.Values); } } string IDataErrorInfo.this[string columnName] { get { return brokenRules[columnName]; } } }
一个明显的改进是将IDataErrorInfo实现移动到类层次结构中,因为它只取决于ValidationEngine,而不依赖于业务对象.
虽然这确实比您提供的简单示例更多的代码,但它还具有相当多的功能,而不仅仅是检查有效性.这给您细粒度,并自动更新指示给用户有关验证问题,并自动禁用“保存”按钮,只要用户尝试输入无效数据.
原文地址:https://www.jb51.cc/html/231118.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。