在WPF中更改按钮形状

时间:2019-07-11 10:47:37

标签: wpf xaml button

我想更改一个按钮,因此它将具有椭圆形状。我正在使用wpf应用。

我看到了一些答案,有人提供了“直截了当”的东西,但我没有得到。此外,我也不想添加图像(这也是问题的答案)。

2 个答案:

答案 0 :(得分:3)

在XAML中尝试以下操作,

    <Button Click="Button_Click">
        <Button.Template>
            <ControlTemplate TargetType="Button">
                <Grid>
                    <Ellipse Fill="{TemplateBinding Background}"/>
                    <ContentPresenter/>
                </Grid>
            </ControlTemplate>
        </Button.Template>
    </Button>

答案 1 :(得分:1)

如果您打算将其应用于单个按钮,则提供的答案是正确的,但真正的问题是,如果要跨多个按钮使用相同的模板,那将是一个问题。为此,请按照以下方法

首先创建一个名为“ Style.xaml”(示例名称)的新资源字典,然后在其中添加以下样式

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                xmlns:local="clr-namespace:SampleCodeWorkSpace">

<Style TargetType="Button" x:Key="EllipseButton">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="Button">
                <Grid>
                    <Ellipse Fill="{TemplateBinding Background}"/>
                    <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center">
                    </ContentPresenter>
                </Grid>
            </ControlTemplate>

        </Setter.Value>
    </Setter>
</Style>

<Style TargetType="Button" x:Key="RoundedButton">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="Button">
                <Border CornerRadius="8" Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}"  
                            BorderThickness="1">
                    <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center">
                    </ContentPresenter>
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

将资源字典引用添加到App.xaml

<Application x:Class="SampleCodeWorkSpace.App"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:local="clr-namespace:SampleCodeWorkSpace"
         StartupUri="MainWindow.xaml">
<Application.Resources>
    <ResourceDictionary Source="Styles.xaml"></ResourceDictionary>
</Application.Resources>

以以下显示方式将样式添加到所需按钮中

<Button Content="Button" Foreground="Black" HorizontalAlignment="Left"  VerticalAlignment="Top" Width="328" Height="188" Click="Button_Click" Style="{StaticResource EllipseButton}" />