ControlTemplate按钮 - 背景不正确

时间:2013-09-08 16:27:31

标签: c# wpf

我正在研究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;

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

enter image description here

我做错了什么?

编辑:点击我的按钮后执行此代码:

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

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

2 个答案:

答案 0 :(得分:1)

您需要为Width严格设置HeightButton。默认情况下,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

enter image description here

答案 1 :(得分: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>