使用IDataErrorInfo进行WPF验证 - 如何删除重复的Validation.ErrorTemplate

时间:2015-12-25 02:41:06

标签: c# wpf validation idataerrorinfo

我正在使用我的WPF表单上的IDataErrorInfo验证所有文本框,如下所示:

<TextBox Name="txtAddress" 
         Validation.Error="Validation_Error"
         Text="{Binding Path=Address, UpdateSourceTrigger=LostFocus, 
                    ValidatesOnDataErrors=True, NotifyOnValidationError=True}">

// If I have many TextBoxes to validate, I have to copy this and paste 
// for each TextBox in XAML.  This obviously violates DRY.  How do I define
// this at one place and use it for all TextBoxes on my form?
    <Validation.ErrorTemplate>
        <ControlTemplate>
            <DockPanel LastChildFill="true">
                <Border Background="Red" DockPanel.Dock="right" Margin="5,0,0,0" Width="16" Height="16" CornerRadius="10"
                    ToolTip="{Binding ElementName=customAdorner, Path=AdornedElement.(Validation.Errors)[0].ErrorContent}">
                    <TextBlock Text="!" 
                               VerticalAlignment="center" HorizontalAlignment="center" 
                               FontWeight="Bold" Foreground="white"/>
                </Border>
                <AdornedElementPlaceholder Name="customAdorner" VerticalAlignment="Center" >
                    <Border BorderBrush="red" BorderThickness="1" />
                </AdornedElementPlaceholder>
            </DockPanel>
        </ControlTemplate>
    </Validation.ErrorTemplate>

</TextBox>

这是我上面使用的Validation_Error方法:

private void Validation_Error(object sender, ValidationErrorEventArgs e)
{
    if (e.Action == ValidationErrorEventAction.Added)
    {
        mNumErrors++;
    }
    else
    {
        mNumErrors--;
    }
}

如果我的表单上有很多文本框,我必须将上面的部分复制到XAML中的每个TextBox定义中。如何在一个地方定义它并将其用于所有TextBox?

谢谢,

1 个答案:

答案 0 :(得分:1)

1路。您可以将ga_dispatchPeriod移动到应用程序或应用程序的窗口。然后像这样添加到textBox ControlTemplate

在资源中使用StaticResource属性

ControlTemplate

x:Key
已分配<ControlTemplate x:Key="MyErrorTemplate"> <DockPanel LastChildFill="true"> <Border Background="Red" DockPanel.Dock="right" Margin="5,0,0,0" Width="16" Height="16" CornerRadius="10" ToolTip="{Binding ElementName=customAdorner, Path=AdornedElement.(Validation.Errors)[0].ErrorContent}"> <TextBlock Text="!" VerticalAlignment="center" HorizontalAlignment="center" FontWeight="Bold" Foreground="white"/> </Border> <AdornedElementPlaceholder Name="customAdorner" VerticalAlignment="Center" > <Border BorderBrush="red" BorderThickness="5" /> </AdornedElementPlaceholder> </DockPanel> </ControlTemplate>

TextBox

ErrorTemplate

2路。如果所有TextBox都应包含此<TextBox Validation.ErrorTemplate="{StaticResource MyErrorTemplate}" /> ,您可以在资源中定义TextBox ErrorTemplate并将Style添加到其中。 ErrorTemplate将应用于所有TextBox。

Style