1

我正在 WPF 中开发一个小型扫雷克隆。对于暴露(即未隐藏)的图块,我有以下样式:

<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>

当用户单击隐藏地雷的图块时,我在代码中设置了地雷的背景颜色:

button.Background = Brushes.OrangeRed;

由于某种原因,而不是整个按钮的背景,只设置了按钮中文本的背景:

在此处输入图像描述

我究竟做错了什么?

编辑:当点击矿井按钮时执行此代码:

button.Style = this.Resources["ExposedTile"] as Style;

if (button == explodedMineTile)
    button.Background = Brushes.OrangeRed;
else
    button.Background = Brushes.DarkOrange;
4

2 回答 2

1

您需要严格设置Widthand Heightfor Button。默认情况下WidthHeight沿内容长度计算。例子:

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

在此处输入图像描述

于 2013-09-08T16:48:31.923 回答
0

我认为您的控件模板中的边框没有您的磁贴的全部宽度。因此,您可以使用模板绑定设置​​边框的宽度。我希望这有效...

<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>
于 2013-09-08T16:47:34.367 回答