我注意到TextBox的一个奇怪的行为,而BorderThickness属性设置为1 - 焦点导致边框改变颜色(像白色).但是,如果我将边框粗细设置为不同于1,例如.99或1.01,问题就会消失.
它是WPF中的错误吗?还是打算?
这是文本框 Aero 样式的默认行为。要禁用它,您需要重新设置文本框的样式。您可以从此处获取默认样式(请参阅下载示例)。
在 TextBoxBase(TextBox 所基于的)的默认样式中,您将看到它使用 ListBoxChrome。该元素在Presentation.Aero 程序集中定义,负责渲染“聚焦”外观。您可以简单地删除 RenderFocus 设置以及可能的 RenderMouseOver,或者将其替换为 Border。
然后您需要将其包含在您的应用程序资源中。
<LinearGradientBrush x:Key="TextBoxBorder"
StartPoint="0,0" EndPoint="0,20" MappingMode="Absolute">
<LinearGradientBrush.GradientStops>
<GradientStop Color="#ABADB3" Offset="0.05" />
<GradientStop Color="#E2E3EA" Offset="0.07" />
<GradientStop Color="#E3E9EF" Offset="1" />
</LinearGradientBrush.GradientStops>
</LinearGradientBrush>
<Style x:Key="{x:Type TextBoxBase}" TargetType="{x:Type TextBoxBase}" BasedOn="{x:Null}">
<Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}" />
<Setter Property="Background" Value="{DynamicResource {x:Static SystemColors.WindowBrushKey}}" />
<Setter Property="BorderBrush" Value="{StaticResource TextBoxBorder}" />
<Setter Property="BorderThickness" Value="1" />
<Setter Property="Padding" Value="1" />
<Setter Property="AllowDrop" Value="true" />
<Setter Property="FocusVisualStyle" Value="{x:Null}" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type TextBoxBase}">
<Border x:Name="Bd" BorderThickness="{TemplateBinding BorderThickness}"
BorderBrush="{TemplateBinding BorderBrush}" Background="{TemplateBinding Background}"
SnapsToDevicePixels="true">
<ScrollViewer x:Name="PART_ContentHost" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" />
</Border >
<ControlTemplate.Triggers>
<Trigger Property="IsEnabled" Value="false">
<Setter TargetName="Bd" Property="Background" Value="{DynamicResource {x:Static SystemColors.ControlBrushKey}}" />
<Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.GrayTextBrushKey}}" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<Style x:Key="{x:Type TextBox}" BasedOn="{StaticResource {x:Type TextBoxBase}}" TargetType="{x:Type TextBox}"/>
Run Code Online (Sandbox Code Playgroud)
如果您查看 Reflector 中的 ListBoxChrome 类(特别是 OnRender 方法),您会发现它仅在 BorderThickness 为“1,1,1,1”时才会渲染聚焦外观。