我有一些图标是我项目中的资源,我打算将这些图标用于菜单项和其他内容。
我创建了一个常量类来将这些图标的位置保存在一个中心位置,而不是将它们硬编码到每个菜单项等中。
例如
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 中引用我的常量?
谢谢, 艾伦
最佳答案
不同之处在于,在第一种情况下(当您对路径进行硬编码时)XAML 解析器将为您在 Source
中指定的字符串调用值转换器 (ImageSourceConverter
)属性将其转换为 ImageSource
类型的值。而在第二种情况下,它期望常量的值已经是 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
对象作为contants并设置BitmapImage
的UriSource
属性到这个 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}"/>
关于c# - WPF图像源来自常量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5127258/