Different versions of this question are already asked, yet solutions to those questions don't feet my requirements.
Assume We have a resource file named MyResource.resx
and an image file Accept.png
in a project folder called Icons
and a refrence to this image is in MyResource.resx
.
I'm looking for a way to set source of an Image UIElement with following requirements:
- Refactor name of image and ...
- Keep it's transparency
- And become aware when I accidentally remove the image file from it's location (compile errors should happen).
Here are what I already tested.
1:In Code behind:
myImage.Source = new BitmapImage(new Uri(@"\Icons\Accept.png", UriKind.Relative));
The problem with this code is: No refactoring is possible, and even worst, errors related to wrong uri are only in run-time.
2: Again in code behind:
myImage.Source = MyResource.Accept.ToBitmapImage()
where .ToBitmapImage()
is a method I've found in internet:
public static BitmapImage ToBitmapImage(this System.Drawing.Bitmap bitmap)
{
using (MemoryStream memory = new MemoryStream())
{
bitmap.Save(memory, ImageFormat.Bmp);
memory.Position = 0;
BitmapImage bitmapImage = new BitmapImage();
bitmapImage.BeginInit();
bitmapImage.StreamSource = memory;
bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
bitmapImage.EndInit();
return bitmapImage;
}
}
The Only problem with this code is that image Transparency is Lost.
In Xaml:
<Image x:Name="myImage" Source="/Icons/Accept.png" />
The problem with this code is: No refactoring is possible, and errors related to wrong uri are not shown. they are not even noticed in runtime.
I tried to use the resource file right in the xaml, following this tutorial but i've failed.
So how to do this.