I have some code which used to work and now doesn’t (don’t know if it’s SL4 -> SL5 or some other update that caused this).
I’m creating MenuItems on the fly for a right-click menu and I’m assigning the icon like so:
public static class XamlUtility
{
public static string makeResourcePngUri(string sName)
{
return "/MyApplication;component/Resources/" + sName + ".png";
}
public static BitmapImage getBitmapImageFromResources(string sName)
{
BitmapImage _bmi = null;
_bmi = new BitmapImage(new Uri(makeResourcePngUri(sName), UriKind.Relative));
return _bmi;
}
public static Image getImageFromResources(string sName)
{
Image _im = new Image();
_im.Source = getBitmapImageFromResources(sName);
return _im;
}
}
public static class XamlUtility
{
public static string makeResourcePngUri(string sName)
{
return "/MyApplication;component/Resources/" + sName + ".png";
}
public static BitmapImage getBitmapImageFromResources(string sName)
{
BitmapImage _bmi = null;
_bmi = new BitmapImage(new Uri(makeResourcePngUri(sName), UriKind.Relative));
return _bmi;
}
public static Image getImageFromResources(string sName)
{
Image _im = new Image();
_im.Source = getBitmapImageFromResources(sName);
return _im;
}
}
...
public static MenuItem addMenuItem(ContextMenu ctxmenu, string name, bool visible = true, MenuClickHandler clickHandler = null, string imageName = null)
{
string _name = name.Replace(' ', '_');
MenuItem menu = new MenuItem()
{
Name = "mnu" + _name,
Header = name,
Icon = XamlUtility.getImageFromResources(imageName ?? _name)
};
…
The image only loads if I have it previously loaded (e.g. create an image control on some xaml form prior to generating the ContextMenu).
This used to work (it wasn’t a high priority to fix so I don’t know when it stopped working)
in your getBitmapImageFromResources method add