【问题标题】:WPF Image source from constant来自常量的 WPF 图像源
【发布时间】:2026-02-09 14:15:01
【问题描述】:

我的项目中有一些图标资源,我计划将这些图标用于菜单项和其他内容。

我创建了一个常量类来将这些图标的位置保存在一个中心位置,而不是将它们硬编码到每个菜单项等中。

例如

public const string IconName = "/Project;component/Icons/IconName.png";

如果我将此值硬编码到 xaml 中图像的 Source 属性中,它可以正常工作。但是,如果我尝试引用此常量,则会失败。

例如

<Image Source="{x:Static pb:IconConstants.IconName}" Width="16" Height="16" />

失败并出现以下异常:“无法将属性 'Source' 中的值转换为 'System.Windows.Media.ImageSource' 类型的对象。”。

这和我只是硬编码值有什么区别?有没有更好的方法在 xaml 中引用我的常量?

谢谢, 艾伦

【问题讨论】:

    标签: c# wpf image xaml constants


    【解决方案1】:

    不同之处在于,在第一种情况下(当您硬编码路径时),XAML 解析器将为您在Source 属性中指定的字符串调用值转换器 (ImageSourceConverter),以将其转换为 @ 类型的值987654323@。而在第二种情况下,它预计常量的值已经是ImageSource 类型。

    你可以做的是你可以把所有的路径放在一个全局的ResourceDictionary

    <Window.Resources>
        <ResourceDictionary>
            <BitmapImage x:Key="IconName">/Project;component/Icons/IconName.png</BitmapImage>
        </ResourceDictionary>
    </Window.Resources>
    

    <Image Source="{StaticResource IconName}" Width="16" Height="16" />
    

    如果要在代码中存储路径常量,可以将Uri 对象作为常量,并将BitmapImageUriSource 属性设置为这个URI:

    public static readonly Uri IconName = new Uri("/Project;component/Icons/IconName.png", UriKind.Relative); 
    

    <BitmapImage x:Key="IconName" UriSource="{x:Static pb:IconConstants.IconName}"/>
    

    【讨论】:

    • 感谢您的回答巴甫洛。我一直在尝试让这个工作,但我仍然收到错误消息“无法将字符串 '/Project;component/Icons/IconName.png' 转换为 'System.Windows.Media.Imaging.BitmapImage' 对象。” .理想情况下,将我的常量存储为字符串会很好,因为我在其他地方使用它们来绑定变量等。我想我可能不得不在此期间不情愿地对它们进行硬编码。
    • 谢谢帕夫洛。这将完成这项工作!非常感谢您的帮助。
    【解决方案2】:

    如果您想将图像指定为资源字典中的资源,则在 Pavlo 提到的基础上稍作修改。如果您在资源字典中直接内联指定图像路径,对于 Windows 8 XAML,它会给出错误

    “错误 1 ​​缺少元素 'BitmapImage' 的内容属性定义 接收内容'/Project;component/Icons/IconName.png'

    要解决它,您必须将路径指定为 UriSource。

    <ResourceDictionary>
      <BitmapImage x:Key="ImageFollowOnFacebook" 
                   UriSource="Assets/FollowOnFacebookImage.png"/>
    </ResourceDictionary>
    

    【讨论】:

      最近更新 更多