在WPF中,如何在TextBox中显示验证错误,如下图所示?

时间:2021-12-25 22:22:27

I have a TextBox bound to some property. I have implemented IDataErrorInfo for performing validation. Recently I was seeing some control in web which shows an error like a red triangle. I have attached the sample below:

我有一个绑定到某个属性的TextBox。我已经实现了IDataErrorInfo来执行验证。最近我在网上看到了一些控制,显示出像红色三角形一样的错误。我附上了以下示例:

在WPF中,如何在TextBox中显示验证错误,如下图所示?

I know I have to write error template to display this whenever an error occurs. When the user hovers the red triangle, it will display the error message in ToolTip. How do I display an error textBox like the one I have uploaded. How to get the red triangle in error template?

我知道我必须编写错误模板,以便在发生错误时显示它。当用户悬停红色三角形时,它将在工具提示中显示错误消息。如何显示错误文本框,就像我上传的文本框一样。如何在错误模板中获取红色三角形?

1 个解决方案

#1


13  

Here is an example that looks like this

这是一个看起来像这样的例子

在WPF中,如何在TextBox中显示验证错误,如下图所示?

Use it like

用它就好

<TextBox Validation.ErrorTemplate="{StaticResource topRightCornerErrorTemplate}"
         .../>

ErrorTemplate

ErrorTemplate

<ControlTemplate x:Key="topRightCornerErrorTemplate">
    <Grid>
        <Polygon Points="40,20 40,0 0,0"
                 Stroke="Black"
                 StrokeThickness="1"
                 Fill="Red"
                 HorizontalAlignment="Right"
                 VerticalAlignment="Top"
                 ToolTip="{Binding ElementName=adorner, 
                                   Path=AdornedElement.(Validation.Errors)[0].ErrorContent}"/>
        <AdornedElementPlaceholder x:Name="adorner"/>
    </Grid>
</ControlTemplate>

#1


13  

Here is an example that looks like this

这是一个看起来像这样的例子

在WPF中,如何在TextBox中显示验证错误,如下图所示?

Use it like

用它就好

<TextBox Validation.ErrorTemplate="{StaticResource topRightCornerErrorTemplate}"
         .../>

ErrorTemplate

ErrorTemplate

<ControlTemplate x:Key="topRightCornerErrorTemplate">
    <Grid>
        <Polygon Points="40,20 40,0 0,0"
                 Stroke="Black"
                 StrokeThickness="1"
                 Fill="Red"
                 HorizontalAlignment="Right"
                 VerticalAlignment="Top"
                 ToolTip="{Binding ElementName=adorner, 
                                   Path=AdornedElement.(Validation.Errors)[0].ErrorContent}"/>
        <AdornedElementPlaceholder x:Name="adorner"/>
    </Grid>
</ControlTemplate>