如何在WPF程序中使用IDataErrorInfo.Error?

27

我有一个像这样的对象:

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 属性很容易:

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

然而,我该如何使用Error属性并适当地显示它?


1
我终于找到了一个解决方法,并在这里发布了一篇文章(http://www.cnblogs.com/guogangj/archive/2013/01/03/2843495.html)。 - guogangj
10
Error属性在WPF中并没有真正的用途。你甚至可以在那里抛出NotImplementedException异常。 WPF使用IDataErrorInfo是因为“它已经存在了”,但仅用于this[]部分。我认为这不是WPF最美好的方面。 - Robin
1
@Robin,你可以回答这个问题。已经过去了3-4年,还没有被接受的答案 ;) - Jeff B
2个回答

9

您应该修改文本框的样式,使其显示属性出错的信息。以下是一个简单示例,它将错误显示为工具提示:

<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 中,它就会应用于您应用程序中的每个文本框:

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

7

以下是一个示例,改编自这个问题,展示了如何在工具提示中显示错误:

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

1
嗨,我在IDataErrorInfo.Error.get处设置了断点,但它从未被触发。怎么回事? - guogangj
1
@jgg - 在这种情况下,Error 可能不会被调用。 IDataErrorInfo.this 会被调用,并且会传递 "PersonName""Age"。因此,您需要处理这两个属性,但现在您只处理前者。 - CodeNaked

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接