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 theSourceattribute 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
Uriobjects as contants and set theUriSourceproperty ofBitmapImageto this URI: