使用XAML图像作为按钮内容



我是Visual Studio的初学者。

我想在我的按钮中有单独的可定义图标。我想只使用XAML来实现这一点,以便尽可能地将我的GUI内容分开。

我希望能够像这样使用它:

<Button x:Name="CallButton" Height="128px" Width="128px" 
        Style="{DynamicResource RoundButton}" Content="{StaticResource PhoneIcon}">

我已经在它们各自的资源词典中定义了RoundButton和PhoneIcon。

圆形按钮:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Style x:Key="RoundButton" TargetType="{x:Type Button}">
        <Setter Property="Content" Value="{Binding Grid}"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type Button}">
                    <Border CornerRadius="100" BorderThickness="2" x:Name="border" 
                            BorderBrush="{TemplateBinding BorderBrush}">
                        <Grid>
                            <ContentPresenter VerticalAlignment="Center" 
                                              HorizontalAlignment="Center" 
                                              x:Name="contentPresenter" Opacity="1" />
                        </Grid>
                    </Border>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</ResourceDictionary>

PhoneIcon:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Canvas x:Key="PhoneIcon">
        <Path Stroke="Gray" Data="m 492.438 397.75 -2.375 -7.156 c -5.625 -16.719 -24.063 -34.156 -41 -38.75 l -62.688 -17.125 c -17 -4.625 -41.25 1.594 -53.688 14.031 L 310 371.438 C 227.547 349.157 162.891 284.5 140.641 202.063 l 22.688 -22.688 c 12.438 -12.438 18.656 -36.656 14.031 -53.656 L 160.266 63 C 155.641 46.031 138.172 27.594 121.485 22.031 l -7.156 -2.406 c -16.719 -5.563 -40.563 0.063 -53 12.5 L 27.391 66.094 c -6.063 6.031 -9.938 23.281 -9.938 23.344 -1.187 107.75 41.063 211.562 117.281 287.781 76.031 76.031 179.453 118.219 286.891 117.313 0.563 0 18.313 -3.813 24.375 -9.844 l 33.938 -33.938 c 12.437 -12.437 18.062 -36.281 12.5 -53 z" />
    </Canvas>
</ResourceDictionary>

我已经在App.xaml:中合并了我的资源词典

<Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="RoundButton.xaml" />
            <ResourceDictionary Source="Icons.xaml" />
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Application.Resources>

我的问题是,当我显示图像时,它太大了。我已经尝试了很多解决方案,所以我开始忘记我的试错方法。

如何使图像显示在正确大小的按钮中心?

NB我已经修剪了我在这里发布的一些代码,但我也测试了我在此处发布的代码,问题仍然存在。

提前感谢!

您可以在PhoneIcon资源中使用Grid而不是Canvas,并设置Path的Stretch属性。这将把路径缩放到符合按钮边界的大小:

<Grid x:Key="PhoneIcon">
    <Path Stretch="Uniform" ... />
</Grid>

您甚至可以明确设置网格大小:

<Grid x:Key="PhoneIcon" Width="80">
    <Path Stretch="Uniform" ... />
</Grid>

一个更简单的解决方案是在没有任何容器的情况下使用Path:

<Path x:Key="PhoneIcon" Width="80" Stretch="Uniform" ... />

最新更新