Reputation: 29421
I'm working on a little Minesweeper clone in WPF. I have the following style for a tile that is exposed (i.e. not hidden):
<Style x:Key="ExposedTile" BasedOn="{StaticResource {x:Static ToolBar.ButtonStyleKey}}" TargetType="Button">
<Setter Property="Control.Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Border Background="{TemplateBinding Background}">
<ContentPresenter />
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
I set the background colour of mines in code when the user clicks on a tile that conceals a mine:
button.Background = Brushes.OrangeRed;
For some reason, instead of the background of the whole button, only the background of the text in the button is being set:
What am I doing wrong?
edit: This code executes when a mine button is clicked:
button.Style = this.Resources["ExposedTile"] as Style;
if (button == explodedMineTile)
button.Background = Brushes.OrangeRed;
else
button.Background = Brushes.DarkOrange;
Upvotes: 1
Views: 99
Reputation: 22702
You need strictly set the Width
and Height
for Button
. By default Width
and Height
is taken along the length of the content. Example:
XAML
<Window.Resources>
<Style x:Key="ExposedTile" BasedOn="{StaticResource {x:Static ToolBar.ButtonStyleKey}}" TargetType="Button">
<Setter Property="Control.Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Border Background="{TemplateBinding Background}">
<ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" Margin="0,5,0,0" />
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
<Grid>
<Button Name="FlatButton"
Width="25"
Height="25"
Content="*" />
</Grid>
Code behind
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Window_ContentRendered(object sender, EventArgs e)
{
FlatButton.Style = this.Resources["ExposedTile"] as Style;
FlatButton.Background = Brushes.Orange;
}
}
Output
Upvotes: 1
Reputation: 101
I think the border in your control template doesn't have the full width of your tile. So you could set the width of the border using template binding. I hope this works...
<Style x:Key="ExposedTile" BasedOn="{StaticResource {x:Static ToolBar.ButtonStyleKey}}" TargetType="Button">
<Setter Property="Control.Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Border Background="{TemplateBinding Background}" Width="{TemplateBinding Width}" Height="{TemplateBinding Height}">
<ContentPresenter />
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
Upvotes: 0