<DrawingImage x:Key="HexagonImage">
<DrawingImage.Drawing>
<DrawingGroup>
<GeometryDrawing Brush="White"
Geometry="M 250,0 L 750,0 L 1000,433 L 750,866 L 250,866 L 0,433 Z">
<GeometryDrawing.Pen>
<Pen Brush="Black" Thickness="10" LineJoin="Round"/>
</GeometryDrawing.Pen>
</GeometryDrawing>
</DrawingGroup>
</DrawingImage.Drawing>
</DrawingImage>
<Style x:Key="HexagonButton" TargetType="{x:Type Button}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Grid>
<Image x:Name="hexImg" Source="{StaticResource HexagonImage}"/>
<ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
我有一个按钮,它有HexagonButton作为它的样式,我想改变它的颜色 以编程方式,Iv'e尝试更改Backgroup属性,但无济于事。
我设法做到的唯一方法是使用新的绘图图像创建一个全新的样式。 并分配它。但我确信有一种更简单的方法可以做到。
答案 0 :(得分:2)
我的工作方式就是将GeomteryDrawing
直接包含在Button
模板中,并使用RelativeSource
绑定到Foreground
和Background
属性它的Button
祖先(我在样式声明中指定了默认值):
<Style x:Key="HexagonButton" TargetType="{x:Type Button}">
<Setter Property="Background" Value="White" />
<Setter Property="Foreground" Value="Black" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Grid>
<Image x:Name="hexImg">
<Image.Source>
<DrawingImage>
<DrawingImage.Drawing>
<DrawingGroup>
<GeometryDrawing Brush="{Binding RelativeSource={RelativeSource AncestorType={x:Type Button}}, Path=Background}" Geometry="M 250,0 L 750,0 L 1000,433 L 750,866 L 250,866 L 0,433 Z">
<GeometryDrawing.Pen>
<Pen Brush="{Binding RelativeSource={RelativeSource AncestorType={x:Type Button}}, Path=Foreground}" Thickness="10" LineJoin="Round" />
</GeometryDrawing.Pen>
</GeometryDrawing>
</DrawingGroup>
</DrawingImage.Drawing>
</DrawingImage>
</Image.Source>
</Image>
<ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" />
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
默认的白色和黑色按钮是:
<Button Style="{StaticResource HexagonButton}">Click me</Button>
自定义按钮是:
<Button Style="{StaticResource HexagonButton}" Background="Yellow" Foreground="Red">Click me</Button>
答案 1 :(得分:1)
如果您只想更改六边形周围的背景,请将Background="{TemplateBinding Background}"
添加到Grid
中的ControlTemplate
。
如果您还想更改六边形内部的背景颜色,请将Brush
的{{1}}更改为GeometryDrawing
。