【问题标题】:How to make circle button in XAML and C# with customize style?如何使用自定义样式在 XAML 和 C# 中制作圆形按钮?
【发布时间】:2024-04-25 03:45:02
【问题描述】:

我是 XAML 的新手,我的简单游戏中的按钮有问题。 我制作了一个圆形按钮,我需要更改它的颜色,但是我的按钮没有给出按钮的默认样式,如动画、悬停时指针更改、单击动画等,它的颜色也不会改变。

这是我的 XAML:

<Page.Resources>
    <SolidColorBrush x:Key="RedColorXX" Color="Red" />
</Page.Resources>

<Button x:Name="btnRed" Style="{StaticResource  btnColor}" Content="Red" HorizontalAlignment="Left" Height="228" Margin="62,261,0,0" VerticalAlignment="Top" Width="228" Background="#FFCA6969" Click="colors_Click" FontSize="0.01" BorderBrush="Azure" Grid.Column="1" >
    <Button.Template >
        <ControlTemplate TargetType="Button" >
            <Grid >
                <Path Stretch="Uniform" UseLayoutRounding="False" Fill="#FFCA6969">
                    <Path.Data>
                        <EllipseGeometry RadiusX="1" RadiusY="1"/>
                    </Path.Data>
                </Path>
                <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/>
            </Grid>
        </ControlTemplate>
    </Button.Template>
</Button>

以及不起作用的颜色更改代码!

btnRed.Background = (SolidColorBrush)Resources["RedColorXX"];

【问题讨论】:

  • 您的点击需要更改椭圆的颜色。在椭圆内试试 Fill="{Binding ElementName=btnRed, Path=Background}"
  • 您可以复制default Button template from MSDN 的一个版本,然后只需将 ControlTemplate 修改为您在此处拥有的内容。这应该为您提供所有默认行为,并为其提供您自己的自定义形状。
  • 这样做时他需要将他的Fill 更改为{TemplateBinding Background},但这绝对是最好的方法。
  • 坦率地说,你在这里问的不是很清楚。你写了“我需要改变它的颜色”,但没有解释你想要改变颜色的时间或原因。您似乎在问如何保留 Button 对象的现有行为,但不清楚您希望“现有行为”如何与“更改其颜色”方面进行交互。请提供一个好的minimal reproducible example,准确地展示您尝试过的内容,并准确、清晰地解释该代码的作用以及您希望它做什么。

标签: c# wpf xaml button geometry


【解决方案1】:

例如我把你的 fill="#FFCA6969" 变成黄色:

<Button x:Name="btnRed"  Content="Red" HorizontalAlignment="Left" Height="228" Margin="100,35,0,0" VerticalAlignment="Top" Width="228" Background="#FFCA6969" Click="colors_Click" FontSize="0.01" BorderBrush="Azure" >
        <Button.Template >
            <ControlTemplate TargetType="Button" >
                <Grid >
                    <Path Stretch="Uniform" UseLayoutRounding="False" Fill="Yellow">
                        <Path.Data>
                            <EllipseGeometry RadiusX="1" RadiusY="1"/>
                        </Path.Data>
                    </Path>
                    <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/>
                </Grid>
            </ControlTemplate>
        </Button.Template>
    </Button>

【讨论】:

  • 这绝对有效...不过我稍微调整了一下以达到我想要的效果。