如何在按钮中添加图标(MahApps)

6

我想将MahApps库中的图标放入普通按钮中。我尝试了以下方法:

<Button Height="20" Width="25" Background="Transparent" Foreground="White" Content="{StaticResource appbar_close}"/>

这个问题的解决方案如下图所示:

那么如何将这个图标集成到适当的位置呢?

你能展示一下 appbar_close 的代码吗?使用 Content="{StaticResource appbar_close}" 我们无法知道你正在使用什么。 - ganchito55
1
这段代码是使用MahApps构建的:http://mahapps.com/guides/icons-and-resources.html - Christian Klemm
5个回答

21

您有两个选择。

首先,您可以使用图标资源(例如MetroCircleButtonStyle样式的示例)。

<Button Width="50"
        Height="50"
        Style="{DynamicResource MetroCircleButtonStyle}">
    <Rectangle Width="20"
                Height="20"
                Fill="{Binding Path=Foreground, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Button}}}">
        <Rectangle.OpacityMask>
            <VisualBrush Stretch="Fill" Visual="{DynamicResource appbar_close}" />
        </Rectangle.OpacityMask>
    </Rectangle>
</Button>

其次是新的图标包

<Button Width="50"
        Height="50"
        Style="{DynamicResource MetroCircleButtonStyle}">
    <Controls:PackIconModern Width="20" Height="20" Kind="Close" />
</Button>

4

正如您在Github示例中所看到的,他们在按钮内部放置了一个矩形,然后使用OpacityMask属性。

<ToggleButton Width="50"
          Height="50"
          IsEnabled="False"
          Style="{DynamicResource MetroCircleToggleButtonStyle}">
<Rectangle Width="20"
           Height="20"
           Fill="{Binding Path=Foreground, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ToggleButton}}}">
    <Rectangle.OpacityMask>
        <VisualBrush Stretch="Fill"
                     Visual="{DynamicResource appbar_city}" />
    </Rectangle.OpacityMask>
</Rectangle>

Source


1
使用 VisualBrush 是比较昂贵的,你可以直接使用 Drawing - Dai

1

在我的应用程序中,我之前使用了以下代码来创建带有图标的大量按钮:

 <Button Command="{Binding EditDetailCommand}" ToolTip="Edit" Style="{DynamicResource buttonstyle}">
                        <metro:PackIconModern Width="Auto" Height="Auto" Kind="Edit" />
                    </Button>

似乎无法与最新的MahApps一起使用了?
我真的很喜欢简单的语法,因为我认为它已经足够填满我的xaml文件了。

我实际上并没有看到新语法和旧语法之间有太大的差异。 - Christian Klemm
矩形(Rectangle)和视觉刷(VisualBrush)包含在样式中吗? - Fam Wired

1
你可以尝试以下方法...就像@ganchito55建议的那样。
<Button Width="25" Height="20">
  <Button.Content>
    <Rectangle Width="20" Height="20">
          <Rectangle.Fill>
            <VisualBrush Visual="{StaticResource appbar_close}" Stretch="None" />
          </Rectangle.Fill>
     </Rectangle>
 </Button.Content>
</Button>

0

我想要将图标仅作为可点击控件,这是在最新的Mahapps版本中对我有效的方法:

<Button Width="16"
        Height="16"
        Padding="0"
        HorizontalAlignment="Right"
        VerticalAlignment="Center"
        Click="HelpButton_Click"
        Style="{x:Null}"
        Background="Transparent"
        BorderThickness="0"
        >
    <Button.Content>
        <Icons:PackIconMaterial Kind="Help"
                                VerticalAlignment="Center"
                                HorizontalAlignment="Center" />
    </Button.Content>
</Button>

希望这能帮助到某个人


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接