WPF ErrorTemplate在失去焦点时是否可见?

4

我是一个WPF文本框验证的助手。我定义了以下模板:

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

文本框位于选项卡中的表单上。 一切都正常,但是当我选择其他选项卡时,“!”文本块仍然可见。在许多其他情况下也观察到此行为-当展开器展开时等等,感叹号始终保持在同一位置可见,尽管文本框未显示。
1个回答

5

This is what we do...

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

2
这里有一个问题!在某些情况下,WPF 在渲染时会抛出异常(无法将 NULL 值添加到集合中)。当我将 TextBox 放在 UserControl 中并将其保存在缓存中,然后重新加载实例时就会发生这种情况。 - theSpyCry

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