XAML 在wpf中更改按钮形状

kx1ctssn  于 2024-01-04  发布在  其他
关注(0)|答案(2)|浏览(214)

我想改变一个按钮,所以它将有椭圆形。我使用wpf应用程序。
我看到了一些答案,有人提供了“简单”的东西,我没有得到它。而且我不想添加图像(这也是对问题的回答)。

46scxncf

46scxncf1#

提供的答案是正确的,如果你打算在单个按钮上应用,但真实的问题,如果你想在多个按钮上使用相同的模板,那么这将是一个问题。为此,请按照下面的方法
首先创建一个名为Styles.xaml的新资源字典(作为示例),并将以下样式添加到其中:

  1. <ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  2. xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  3. xmlns:local="clr-namespace:SampleCodeWorkSpace">
  4. <Style TargetType="Button" x:Key="EllipseButton">
  5. <Setter Property="Template">
  6. <Setter.Value>
  7. <ControlTemplate TargetType="Button">
  8. <Grid>
  9. <Ellipse Fill="{TemplateBinding Background}"/>
  10. <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center">
  11. </ContentPresenter>
  12. </Grid>
  13. </ControlTemplate>
  14. </Setter.Value>
  15. </Setter>
  16. </Style>
  17. <Style TargetType="Button" x:Key="RoundedButton">
  18. <Setter Property="Template">
  19. <Setter.Value>
  20. <ControlTemplate TargetType="Button">
  21. <Border CornerRadius="8" Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}"
  22. BorderThickness="1">
  23. <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center">
  24. </ContentPresenter>
  25. </Border>
  26. </ControlTemplate>
  27. </Setter.Value>
  28. </Setter>
  29. </Style>
  30. </ResourceDictionary>

字符串
接下来,将资源字典引用添加到App.xaml

  1. <Application x:Class="SampleCodeWorkSpace.App"
  2. xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  3. xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  4. xmlns:local="clr-namespace:SampleCodeWorkSpace"
  5. StartupUri="MainWindow.xaml">
  6. <Application.Resources>
  7. <ResourceDictionary Source="Styles.xaml"></ResourceDictionary>
  8. </Application.Resources>


最后,将样式添加到所需按钮,如下所示

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


App.xamlStyle.xaml中,确保将xmlns:local更改为项目的命名空间

展开查看全部
nfzehxib

nfzehxib2#

在XAML中尝试以下操作:

  1. <Button Click="Button_Click">
  2. <Button.Template>
  3. <ControlTemplate TargetType="Button">
  4. <Grid>
  5. <Ellipse Fill="{TemplateBinding Background}"/>
  6. <ContentPresenter/>
  7. </Grid>
  8. </ControlTemplate>
  9. </Button.Template>
  10. </Button>

字符串

相关问题