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

Avalonia 11:如何使用依赖主题的ResourceDictionary定义的图片

问题原因与解决方案

核心错误

你定义的SomeImage资源是ImageBrush类型,但Image控件的Source属性需要的是IImage类型(比如Uri、Bitmap这类图片源对象),ImageBrush是用来填充UI区域的画刷,并非图片源,因此绑定后不会报错但也无法显示图片。

正确实现方式

方法1:通过主题字典定义图片源资源

修改Styles.axaml,在Light和Dark主题字典中定义Uri或Bitmap类型的资源,而非ImageBrush:

<Styles xmlns="https://github.com/avaloniaui"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
  <StyleInclude Source="avares://Avalonia.Themes.Fluent/Fluent.xaml"/>

  <Style>
    <Style.Resources>
      <!-- 浅色主题图片 -->
      <ThemeDictionary x:Key="Light">
        <Uri x:Key="SomeImage">avares://YourAppNamespace/Assets/light-mode-image.png</Uri>
      </ThemeDictionary>
      <!-- 深色主题图片 -->
      <ThemeDictionary x:Key="Dark">
        <Uri x:Key="SomeImage">avares://YourAppNamespace/Assets/dark-mode-image.png</Uri>
      </ThemeDictionary>
    </Style.Resources>
  </Style>
</Styles>

方法2:通过控件样式触发器切换

若不想依赖主题字典,可直接给Image控件添加触发器,根据深色模式状态切换Source:

<Image Width="120" Height="120">
  <Image.Styles>
    <Style Selector="Image">
      <Setter Property="Source" Value="avares://YourAppNamespace/Assets/light-mode-image.png"/>
      <Style.Triggers>
        <Trigger Property="IsDarkMode" Value="True">
          <Setter Property="Source" Value="avares://YourAppNamespace/Assets/dark-mode-image.png"/>
        </Trigger>
      </Style.Triggers>
    </Style>
  </Image.Styles>
</Image>

关键注意事项

  • 图片文件的构建操作必须设为Resource:右键图片文件 → 属性 → 构建操作 → 选择Resource,否则无法通过avares://路径访问。
  • 替换代码中的YourAppNamespace为你的项目命名空间,图片路径需与实际文件位置一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 14:12:11