WPF: programmatically change color of a control with a custom style
<DrawingImage x:Key="HexagonImage">
<DrawingImage.Drawing>
<DrawingGroup>
开发者_Go百科 <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>
I have a button, that has this HexagonButton as its style, and I want to change its color programmatically, Iv'e tried changing the Backgroup property, but to no avail.
the only way I managed to do so, is to create a whole new style, with a new Drawing image. and assign it. But I'm certain there is an easier way to do so.
I got it to work like by including the GeomteryDrawing
directly in the Button
template, and using RelativeSource
bindings to the Foreground
and Background
properties of its Button
ancestor (to which I assigned defaults in the style declaration):
<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>
The default white and black button is then:
<Button Style="{StaticResource HexagonButton}">Click me</Button>
And a custom button is:
<Button Style="{StaticResource HexagonButton}" Background="Yellow" Foreground="Red">Click me</Button>
If you want to change the background only around the hexagon, add Background="{TemplateBinding Background}"
to the Grid
in your ControlTemplate
.
If you also want to change the background color of the inside of the hexagon, change the Brush
of your GeometryDrawing
to Transparent
.
精彩评论