WPF ErrorTemplate在没有聚焦时可见?

PaN*_*1Me 4 validation wpf templates focus

我正在使用WPF验证进行TextBox验证.我已经定义了这个模板:

<Style x:Key="textBoxInError" TargetType="{x:Type TextBox}" BasedOn="{StaticResource StyleTextBox}">        
        <Style.Triggers>
            <Trigger Property="Validation.HasError" Value="true">
                <Setter Property="ToolTip"
                        Value="{Binding RelativeSource={x:Static RelativeSource.Self},
                        Path=(Validation.Errors)[0].ErrorContent}"/>
                <Setter Property="Background" Value="{StaticResource TextBox_ErrorBackgroundBrush}"/>
                <Setter Property="BorderBrush" Value="{StaticResource TextBox_ErrorBorderBrush}"/>
                <Setter Property="BorderThickness" Value="2"/>                      
            </Trigger>
        </Style.Triggers>
        <Setter Property="Validation.ErrorTemplate">
            <Setter.Value>
                <ControlTemplate>
                    <DockPanel>
                        <TextBlock DockPanel.Dock="Right" Foreground="Red" FontSize="20" Text="!"/>
                        <AdornedElementPlaceholder/>
                    </DockPanel>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>  
Run Code Online (Sandbox Code Playgroud)

TextBox位于TabItem中的表单上.一切正常,但'!' 当我选择其他TabItem时,TextBlock保持可见.在许多其他情况下会观察到这种行为 - 当扩展器扩展等时.虽然TextBox没有显示,但Excklamation始终在同一个地方保持可见.

小智 5

这就是我们做的......

<Style x:Key="ErrorTemplate" TargetType="Control">
    <Setter Property="Validation.ErrorTemplate">
        <Setter.Value>
            <!--Set your error template in here-->
        </Setter.Value>
    </Setter>
    <Style.Triggers>
        <Trigger Property="IsVisible" Value="false">
            <Setter Property="Validation.ErrorTemplate" Value="{x:Null}"/>
        </Trigger>
    </Style.Triggers>
</Style>
Run Code Online (Sandbox Code Playgroud)

  • 这有一个问题!在某些情况下,WPF通过呈现抛出和异常(不能向集合添加NULL值).当我在UserControl中有TextBox并将其保存在缓存中并从缓存中重新加载实例时,就会发生这种情况. (2认同)