整个表单的 WPF 验证 [英] WPF Validation for the whole form

查看:40
本文介绍了整个表单的 WPF 验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 WPF 验证系统感到非常失望.反正!如何通过单击按钮"来验证完整的表单?

I have been seriously disappointed with WPF validation system. Anyway! How can I validate the complete form by clicking the "button"?

出于某种原因,WPF 中的一切都太复杂了!我可以在 ASP.NET 中用 1 行代码进行验证,而在 WPF 中需要 10-20 行代码!!

For some reason everything in WPF is soo complicated! I can do the validation in 1 line of code in ASP.NET which requires like 10-20 lines of code in WPF!!

我可以使用我自己的 ValidationEngine 框架来做到这一点:

I can do this using my own ValidationEngine framework:

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.

A WPF application should disable the button to submit a form iff the entered data is not valid. You can achieve this by implementing the IDataErrorInfo interface on your business object, using Bindings with ValidatesOnDataErrors=true. For customizing the look of individual controls in the case of errors, set a Validation.ErrorTemplate.

<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, ValidatesOnDataErrors=true, UpdateSourceTrigger=PropertyChanged}" />
        <Button Command="ApplicationCommands.Save" IsDefault="True">Save</Button>
        <TextBlock Text="{Binding Error}"/>
    </StackPanel>
</Window>

这将创建一个带有两个 TextBoxWindow,您可以在其中编辑客户的名字和姓氏.保存"按钮仅在未发生验证错误时才启用.按钮下方的 TextBlock 显示当前错误,因此用户知道发生了什么.

This creates a Window with two TextBoxes where you can edit the first and last name of a customer. The "Save" button is only enabled if no validation errors have occurred. The TextBlock beneath the button shows the current errors, so the user knows what's up.

默认的ErrorTemplate 是错误控件周围的红色细边框.如果这不符合您的视觉概念,请查看 Windows Presentation Foundation 中的验证 关于 CodeProject 的文章,深入了解可以做些什么.

The default ErrorTemplate is a thin red border around the erroneous Control. If that doesn't fit into you visual concept, look at Validation in Windows Presentation Foundation article on CodeProject for an in-depth look into what can be done about that.

要让窗口真正起作用,窗口和客户中必须有一些基础设施.

To get the window to actually work, there has to be a bit infrastructure in the Window and the Customer.

// 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,而不依赖于业务对象.

An obvious improvement would be to move the IDataErrorInfo implementation up the class hierarchy, since it only depends on the ValidationEngine, but not the business object.

虽然这确实比您提供的简单示例代码更多,但它也具有比仅检查有效性更多的功能.这将为您提供有关验证问题的细粒度且自动更新的指示,并在用户尝试输入无效数据时自动禁用保存"按钮.

While this is indeed more code than the simple example you provided, it also has quite a bit more of functionality than only checking for validity. This gives you fine grained, and automatically updated indications to the user about validation problems and automatically disables the "Save" button as long as the user tries to enter invalid data.

这篇关于整个表单的 WPF 验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆