【发布时间】:2023-03-09 09:15:01
【问题描述】:
我在表单中使用<Separator />,但不知道如何更改其颜色。 Border /Foreground/Background 都不存在。请帮忙。
【问题讨论】:
我在表单中使用<Separator />,但不知道如何更改其颜色。 Border /Foreground/Background 都不存在。请帮忙。
【问题讨论】:
嗯...我认为Separator 是少数无法使用简单样式的元素之一。根据 MSDN 文档,您需要指定SeparatorStyleKey。
例如,对于ToolBar,您可以这样做:
<Style x:Key="{x:Static ToolBar.SeparatorStyleKey}"
TargetType="{x:Type Separator}">
<Setter Property="Background"
Value="{DynamicResource {x:Static SystemColors.ControlDarkBrushKey}}"/>
<Setter Property="Margin" Value="0,2,0,2"/>
<Setter Property="Focusable" Value="false"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Separator}">
<Border
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}"
Background="{TemplateBinding Background}"
Height="1"
SnapsToDevicePixels="true"/>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
【讨论】:
您可以使用以下代码设置Separator 的颜色:
<Separator BorderBrush="Red" BorderThickness="1"/>
注意BorderThickness 属性也必须应用。
【讨论】:
BorderThickness="1 0 0 0" 来实现它。否则,分隔符厚两个像素。
BorderThickness="0 1 0 0"。此外,UseLayoutRounding 可能是必要的以避免外观模糊。
你可以设置背景:
<Separator Background="Red"/>
【讨论】:
您也可以选择使用 Rectangle 元素:
<Rectangle HorizontalAlignment="Stretch" Fill="Blue" Height="2"/>
修改/形状稍微容易一些。
【讨论】:
使用样式
<Style x:Key="MySeparatorStyle" TargetType="{x:Type Separator}">
<Setter Property="Background" Value="{DynamicResource {x:Static SystemColors.ControlDarkBrushKey}}"/>
<Setter Property="Margin" Value="0,2,0,2"/>
<Setter Property="Focusable" Value="false"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Separator}">
<Border
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}"
Background="{TemplateBinding Background}"
Height="1"
SnapsToDevicePixels="true"/>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
分隔符只是一个边框元素,现在您可以随意更改其外观?
【讨论】: