WPF 图片来源来自constant
我有一些图标是我的项目中的资源,我计划将这些图标用于菜单项和其他内容。
我创建了一个常量类来将这些图标的位置保存在中心位置,而不是将它们硬编码到每个菜单项等中。
例如,
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 中引用我的常量?
谢谢, 艾伦
I've got some icons that are resources in my project and I plan to use these icons for menu items and other things.
I've created a constants class to hold the locations of these icons in a central location rather than hardcoding them into each menu item etc.
E.g.
public const string IconName = "/Project;component/Icons/IconName.png";
If I hardcode this value into the Source property of an image in xaml it works fine. However, if I try to reference this constant then it fails.
E.g.
<Image Source="{x:Static pb:IconConstants.IconName}" Width="16" Height="16" />
It fails with this exception: "Cannot convert the value in attribute 'Source' to object of type 'System.Windows.Media.ImageSource'. ".
What is the difference between this and me just hardcoding the value? Is there a better way of referencing my constants in xaml?
Thanks,
Alan
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
区别在于,在第一种情况下(当您对路径进行硬编码时),XAML 解析器将为您在
Source
属性中指定的字符串调用值转换器 (ImageSourceConverter
) 进行转换它为ImageSource
类型的值。而在第二种情况下,它期望常量的值已经是ImageSource
类型。您可以做的是将所有路径放入全局
ResourceDictionary
中:如果要在代码中存储路径常量,可以将
Uri
对象作为常量,并将BitmapImage
的UriSource
属性设置为此 URI :The difference is that in first case (when you hardcode the path) the XAML parser will invoke a value converter (
ImageSourceConverter
) for the string you specify in theSource
attribute to convert it to a value of typeImageSource
. While in second case it expects that value of your constant will already be of typeImageSource
.What you can do is you can put all the paths in a global
ResourceDictionary
:If you want to store the path constants in the code, you can have
Uri
objects as contants and set theUriSource
property ofBitmapImage
to this URI:如果你想将图像指定为资源字典中的资源,则在 Pavlo 提到的基础上稍作修改。如果您直接在资源字典中内联指定图像路径,对于 Windows 8 XAML 会出现错误
要解析它,您必须将路径指定为 UriSource。
If you want to specify image as a resource in resource dictionary, there is a slight modification on top of what Pavlo mentioned. If you specify image path directly inline in the resource dictionary, for Windows 8 XAML it gives error
To resolve it, you will have to specify path as UriSource.