自定义按钮而不添加边框或其他内容

问题描述 投票:0回答:1

我有WPF按钮

<Button Style="{StaticResource BrandedButton}">Continue</Button>

其当前样式如下:

<Style x:Key="BrandedButton" TargetType="{x:Type Button}">
    <Setter Property="Background" Value="{StaticResource LowlightBrush}"/>
    <Setter Property="Foreground" Value="White"/>
    <Setter Property="FontFamily" Value="Open Sans Light"/>
    <Setter Property="FontSize" Value="35"/>
    <Setter Property="Padding" Value="50,10"/>
</Style>

enter image description here

现在,我想控制悬停/新闻/等的颜色(没有其他功能,所以我添加了另一个设置器

    <Setter Property="Template" Value="{StaticResource BrandedButtonTemplate}"/>

并且指向此ControlTemplate。我仅看到了更改按钮结构的示例,例如,通过添加边框:

<ControlTemplate x:Key="BrandedButtonTemplate" TargetType="Button">
    <Border Background="{TemplateBinding Background}" BorderBrush="Black" BorderThickness="0">
        <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/>
    </Border>
    <ControlTemplate.Triggers>
        <Trigger Property="IsMouseOver" Value="true">
            <Setter Property="Background" Value="{StaticResource HighlightBrush}"/>
        </Trigger>
        <Trigger Property="IsPressed" Value="true">
            <Setter Property="Background" Value="{StaticResource HighlightBrush}"/>
        </Trigger>
        <Trigger Property="IsEnabled" Value="false">
            <Setter Property="Background" Value="{StaticResource HighlightBrush}"/>
        </Trigger>
    </ControlTemplate.Triggers>
</ControlTemplate>

但是那会杀死以前应用的布局:

enter image description here

相反,如果我仅包含ContentPresenter,而省略了换行Border,则按钮将完全消失。

如何更改悬停并按颜色而不更改其他任何内容?对于一件琐碎的任务,最小/最轻的实现是什么?

wpf xaml user-controls
1个回答
0
投票

您的ControlTemplate忽略Button的Padding属性。

添加ContentPresenter的Margin的模板绑定:

<ControlTemplate x:Key="BrandedButtonTemplate" TargetType="Button">
    <Border Background="{TemplateBinding Background}" BorderThickness="0">
        <ContentPresenter
            Margin="{TemplateBinding Padding}"
            HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
            VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
    </Border>
    <ControlTemplate.Triggers>
        ...
    </ControlTemplate.Triggers>
</ControlTemplate>
© www.soinside.com 2019 - 2024. All rights reserved.