非常简单的 WPF 表单数据验证 - 如何? [英] Really simple WPF form data validation - how to?

查看:43
本文介绍了非常简单的 WPF 表单数据验证 - 如何?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常简单的类,我们称之为客户.它看起来像这样:

I'm having this really simple class, lets call it Customer. It look like this:

namespace TestValidation
{
     class Customer
     {
        private string _name;
        public string Name
        {
            get { return _name; }
            set
            {
                _name = value;
                if (String.IsNullOrEmpty(value))
                {
                    throw new Exception("Customer name is mandatory.");
                }
            }
        }
    }
}

现在,我已经创建了一个基本表单,用户可以在其中将客户添加到数据库中.该表单包含简单的 TextBox,绑定到 Customer 的 Name 属性,以及一个添加"按钮.

Now, I've created a basic form, where the user can add customers to the database. The form contain simple TextBox, bounded to the Name property of Customer, and an "Add" button.

XAML 代码是:

<Window x:Class="TestValidation.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:TestValidation"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
<TextBox Margin="119,86,107,194" Name="CustomerName"
        Text="{Binding Path=Customer.Name, 
                ValidatesOnExceptions=True, 
                ValidatesOnDataErrors=True,
                UpdateSourceTrigger=PropertyChanged,
                NotifyOnValidationError=True}"
    />
        <Button Content="Add" HorizontalAlignment="Left" Margin="204,176,0,0" VerticalAlignment="Top" Width="74"/>
    </Grid>
</Window> 

从 Name 属性的 setter 中,你可以理解 name 对我来说是强制性的,所以如果 Name TextBox 留空,我希望一个验证事件上升.根据 WPF 的验证规则 - 一旦用户将焦点移出文本框,并且那里没有值 - 它应该将边框颜色更改为红色.出于某种原因 - 这没有发生,我不知道为什么.我的流程有什么问题?

From the setter of the Name property, you can understand that the name is mandatory for me, so I want an validation event to rise if the Name TextBox left blank. By validation rules of WPF - once the user focus out of the textbox, and there's no value over there - it should change the border color to red. For some reason - this is not happening, and I don't have a clue why. What is wrong in my process?

现在,我已经阅读了很多关于 WPF 验证的好文章(例如 使用 WPF 实施复杂的业务数据规则数据验证WPF 和 Windows Presentation Foundation 中的验证),但它们都没有帮助我解决我的问题.

Now, I've read so many good articles about Validation in WPF (like Enforcing Complex Business Data Rules with WPF, Data validation in WPF and Validation in Windows Presentation Foundation), but none of them helped me solving my problem.

最终,我希望表单看起来像 Brian Noyes 在第一个链接上的优秀文章中的表单(没有 10 个学分,所以我无法附上照片......抱歉).

Eventually, I want the form to look like the form in Brian Noyes excellent article over the first link (Don't have 10 credits, so I can't attach a photo... sorry).

如果有人能向我解释它是如何工作的,我将不胜感激.

I'll be grateful if someone can explain to me how it really works.

重要说明 - 我正在使用 .Net framework 4,所以我需要一个适合这个版本的解决方案.

Important note - I'm working with .Net framework 4, so I need a solution that suits this version.

推荐答案

我绝对推荐使用 IDataErrorInfo 用于 WPF 验证,因为 WPF 已经了解如何使用它,并且易于实现.

I would definitely recommend using IDataErrorInfo for WPF validation since WPF already understands how to use it, and its easy to implement.

首先,将接口添加到包含要验证的数据的类中.所需的方法可能如下所示:

To start with, add the interface to the class containing the data you want to validate. The required methods will probably look something like this:

public class Customer : IDataErrorInfo
{
    ...

    #region IDataErrorInfo Members

    string IDataErrorInfo.Error
    {
        get { return null; }
    }

    string IDataErrorInfo.this[string columnName]
    {
        get
        {
            if (columnName == "Name")
            {
                // Validate property and return a string if there is an error
                if (string.IsNullOrEmpty(Name))
                    return "Name is Required";
            }

            // If there's no error, null gets returned
            return null;
        }
    }
    #endregion
}

接下来,您需要在 TextBox 绑定中设置 ValidatesOnDataErrors=True,以便它在 Name 属性更改时运行验证:

Next, you need to set ValidatesOnDataErrors=True in your TextBox binding so it runs the validation whenever the Name property changes:

<TextBox Text="{Binding Path=Customer.Name, ValidatesOnDataErrors=True}" ... />

最后,在您的 XAML 中创建一个验证模板,以告诉 WPF 如何绘制验证错误.这是我通常使用的样式/模板:

And finally, create a Validation Template in your XAML to tell WPF how to draw a validation error. Here's the style/template I usually use:

<!-- ValidatingControl Style -->
<Style TargetType="{x:Type FrameworkElement}" x:Key="ValidatingControl">
    <Style.Triggers>
        <Trigger Property="Validation.HasError" Value="True">
            <Setter Property="ToolTip" Value="{Binding 
                Path=(Validation.Errors)[0].ErrorContent, 
                RelativeSource={x:Static RelativeSource.Self}}" />
        </Trigger>
    </Style.Triggers>
</Style>

此外,请确保您的 Customer 类实现了 INotifyPropertyChanged,以便它正确响应 UI 更新.我在您的代码中没有看到这一点,但为了简单起见,人们通常会忽略这一点:)

Also, be sure your Customer class implements INotifyPropertyChanged so it correctly responds to UI updates. I don't see that in your code, but often people leave that out for simplicity :)

这篇关于非常简单的 WPF 表单数据验证 - 如何?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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