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
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 the Source
attribute to convert it to a value of type ImageSource
. While in second case it expects that value of your constant will already be of type ImageSource
.
What you can do is you can put all the paths in a global 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" />
If you want to store the path constants in the code, you can have Uri
objects as contants and set the UriSource
property of BitmapImage
to this 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}"/>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With