How to use IDataErrorInfo.Error in a WPF program?

爱⌒轻易说出口 提交于 2019-11-26 12:43:55

问题


I have an object like that:

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;
        }
    }
}

Binding the PersonName and Age properties is easy:

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

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


回答1:


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>

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>



回答2:


Here is an example, adapted from this question, that shows how to display the error in Tooltip:

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


来源:https://stackoverflow.com/questions/14023552/how-to-use-idataerrorinfo-error-in-a-wpf-program

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!