很简单的WPF窗体数据验证 - 如何? [英] Really simple WPF form data validation - how to?

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

问题描述

我真的很新的这整个WPF的事情,所以我的问题可能是愚蠢的,但请与我裸...我在这个非常简单的类
,让我们把它叫做客户。
它是这样的:

I'm really new to this whole WPF thing, so my problem is probably silly, but please bare with me... 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.");
                }
            }
        }
    }
}

现在,我已经创建了一个基本形式,用户可以在其中客户添加到数据库。该表格​​包含简单的文本框,一定到客户的名称属性,和一个添加按钮

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> 



从名称setter方法​​,可以了解该名称是强制性的我,所以我想要一个验证事件上升,如果名称的文本框留空。通过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.

最后,我希望表单看起来像布莱恩·诺伊斯在第一个环节优秀文章的形式(不要有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
}



接下来,你需要设置 ValidatesOnDataErrors = TRUE 在文本框的结合使其运行验证每当名称属性更改:

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>



另外,确保你的客户类实现 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天全站免登陆