You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用资源字典中的Canvas设置BitmapIcon或PathIcon的内容?

如何用资源字典中的Canvas设置AppBarButton的图标?

你没法直接用BitmapIcon来加载资源字典里的Canvas——因为BitmapIcon是专门用来显示位图图像(比如PNG、JPG)的,它的Source属性只接受图像源,完全不支持UIElement类型的内容。不过有两种更合适的方案能实现你的需求:

方案1:直接将Canvas作为AppBarButton的Icon

AppBarButton.Icon属性本身就支持任何UIElement,所以你可以直接引用资源字典里的Canvas,不需要额外包装:

<AppBarButton Label="Canvas Icon" Click="AppBarButton_Click">
    <AppBarButton.Icon>
        <StaticResource ResourceKey="appbaricon"/>
    </AppBarButton.Icon>
</AppBarButton>

如果你的Canvas尺寸和AppBar图标默认尺寸(通常20x20)不匹配,建议套个Viewbox来自动缩放适配:

<AppBarButton Label="Canvas Icon" Click="AppBarButton_Click">
    <AppBarButton.Icon>
        <Viewbox Width="20" Height="20">
            <StaticResource ResourceKey="appbaricon"/>
        </Viewbox>
    </AppBarButton.Icon>
</AppBarButton>

方案2:改用PathIcon(最佳实践)

既然你的Canvas里只有一个Path,不如直接把Path的Data提取出来作为资源,然后用PathIcon来显示——这是UWP/WinUI里显示矢量图标的标准方式,性能和适配性都更好:

首先修改资源字典,存储Geometry类型的路径数据:

<ResourceDictionary ...>
    <Geometry x:Key="appbariconGeometry">F1 M 25.3333,42.75C 26.5189, ...</Geometry>
</ResourceDictionary>

然后在AppBarButton中使用PathIcon:

<AppBarButton Label="PathIcon" Click="AppBarButton_Click">
    <AppBarButton.Icon>
        <PathIcon Data="{StaticResource appbariconGeometry}" Foreground="#FF000000"/>
    </AppBarButton.Icon>
</AppBarButton>

内容的提问来源于stack exchange,提问作者Bimo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 10:09:35