【发布时间】:2011-10-18 14:32:52
【问题描述】:
我已经建立了一个用户控件。当发生验证错误时,我不喜欢在它周围显示红色边框。我的控件中有一个文本框。
如何覆盖验证错误样式以消除整个控件中的红色边框,只在我的用户控件内的文本框中显示红色背景?
谢谢!
【问题讨论】:
标签: wpf
我已经建立了一个用户控件。当发生验证错误时,我不喜欢在它周围显示红色边框。我的控件中有一个文本框。
如何覆盖验证错误样式以消除整个控件中的红色边框,只在我的用户控件内的文本框中显示红色背景?
谢谢!
【问题讨论】:
标签: wpf
我正在使用这个模板,它将为文本框的背景着色,而不是只显示边框。
<UserControl.Resources>
<Style TargetType="{x:Type TextBox}">
<Style.Triggers>
<Trigger Property="Validation.HasError" Value="true" >
<Setter Property="Foreground" Value="Red"/>
<Setter Property="Background" Value="MistyRose"/>
<Setter Property="BorderBrush" Value="Red"/>
<Setter Property="BorderThickness" Value="1.0"/>
<Setter Property="VerticalContentAlignment" Value="Center"/>
<Setter Property="ToolTip" Value="{Binding RelativeSource={RelativeSource
Self},Path=(Validation.Errors)[0].ErrorContent}"/>
</Trigger>
</Style.Triggers>
</Style>
</UserControl.Resources>
我必须对你的 DocPanel 做的所有事情例如,对于我来说,控件位于 DockPanel 内,然后我必须将其 Validation.Error 模板设置为空,这将删除边框。
例如:
<TextBox >
<Validation.ErrorTemplate>
<ControlTemplate>
</ControlTemplate>
</Validation.ErrorTemplate>
</TextBox>
【讨论】:
Validation.ErrorTemplate。假设例如用户控件的 Root_LayoutContainer 是网格然后设置网格的 Validtion.ErrorTemplate 你不应该在你的用户控件上看到这个了。
关于用户控件的样式:
<Setter Property="Validation.ErrorTemplate" Value="{x:Null}"/>
关于文本框的样式:
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type TextBoxBase}">
<Border
Name="Border"
CornerRadius="5"
Padding="2"
BorderBrush="{TemplateBinding BorderBrush}"
Background="{TemplateBinding Background}"
BorderThickness="{TemplateBinding BorderThickness}" >
<ScrollViewer Margin="0" x:Name="PART_ContentHost"/>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsEnabled" Value="False">
<Setter TargetName="Border" Property="Background" Value="LightGray"/>
<Setter TargetName="Border" Property="BorderBrush" Value="Black"/>
<Setter Property="Foreground" Value="Gray"/>
</Trigger>
<Trigger Property="Validation.HasError" Value="true">
<Setter Property="BorderBrush" TargetName="Border" Value="{DynamicResource ErrorBorderColor}"/>
<Setter Property="Background" TargetName="Border" Value="{DynamicResource ErrorBackgroundColor}"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
【讨论】: