如何在 WPF 程序中使用 IDataErrorInfo.Error? [英] How to use IDataErrorInfo.Error in a WPF program?

查看:27
本文介绍了如何在 WPF 程序中使用 IDataErrorInfo.Error?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的对象:

public class Person : IDataErrorInfo
{
    public string PersonName{get;set;}
    public int Age{get;set;}

    string IDataErrorInfo.this[string propertyName]
    {
        get
        {
            if(propertyName=="PersonName")
            {
                if(PersonName.Length>30 || PersonName.Length<1)
                {
                    return "Name is required and less than 30 characters.";
                }
            }
            return null;
        }
    }

    string IDataErrorInfo.Error
    {
        get
        {
            if(PersonName=="Tom" && Age!=30)
            {
                return "Tom must be 30.";
            }
            return null;
        }
    }
}

绑定 PersonName 和 Age 属性很容易:

Binding the PersonName and Age properties is easy:

<TextBox Text="{Binding PersonName, ValidatesOnDataErrors=True}" />
<TextBox Text="{Binding Age, ValidatesOnDataErrors=True}" />

但是,我如何使用 Error 属性并适当地显示它?

However, how can I use the Error property and show it appropriately?

推荐答案

您应该修改 TextBox 样式,以便它显示属性有什么问题.这是一个简单的示例,将错误显示为工具提示:

You should modify the TextBox style so it shows what's wrong with the property. Here is a simple example that shows the error as tooltip:

<Style TargetType="TextBox">
        <Style.Triggers>
            <Trigger Property="Validation.HasError" Value="true">
                <Setter Property="ToolTip" Value="{Binding RelativeSource={RelativeSource Self},
                        Path=(Validation.Errors).CurrentItem.ErrorContent}" />
            </Trigger>
        </Style.Triggers>
</Style>

只需将它放在 app.xaml 文件中的 Application.Resources 中,它就会应用于应用程序的每个文本框:

Just put it inside Application.Resources from your app.xaml file and it will be aplied for every textbox of your application:

<Application.Resources>
    <Style TargetType="TextBox">
            <Style.Triggers>
                <Trigger Property="Validation.HasError" Value="true">
                    <Setter Property="ToolTip" Value="{Binding RelativeSource={RelativeSource Self},
                            Path=(Validation.Errors).CurrentItem.ErrorContent}" />
                </Trigger>
            </Style.Triggers>
    </Style>
</Application.Resources>

这篇关于如何在 WPF 程序中使用 IDataErrorInfo.Error?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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