WPF image resources
I come from a mostly web and a little bit Windows Forms background. For a new project, we will be using WPF. The WPF application will need 10 - 20 small icons and images for illustrative purposes. I am thinking about storing these in the assembly as embedded resources. Is that the right way to go ?
How do I specify in XAML that an Image control should load the image from an embedded resource ?
If you will use the image in multiple places, then it's worth loading the image data only once into memory and then sharing it between all Image
elements.
To do this, create a BitmapSource
as a resource somewhere:
<BitmapImage x:Key="MyImageSource" UriSource="../Media/Image.png" />
Then, in your code, use something like:
<Image Source="{StaticResource MyImageSource}" />
In my case, I found that I had to set the Image.png
file to have a build action of Resource
rather than just Content
. This causes the image to be carried within your compiled assembly.
I found to be the best practice of using Images,Video,etc is:
Example
<Image Source="/WPFApplication;component/Images/Start.png" />
Benefits:
Some people are asking about doing this in code and not getting an answer.
After spending many hours searching I found a very simple method, I found no example and so I share mine here which works with images. (mine was a .gif)
Summary:
It returns a BitmapFrame which ImageSource "destinations" seem to like.
Use:
doGetImageSourceFromResource ("[YourAssemblyNameHere]", "[YourResourceNameHere]");
Method:
static internal ImageSource doGetImageSourceFromResource(string psAssemblyName, string psResourceName)
{
Uri oUri = new Uri("pack://application:,,,/" +psAssemblyName +";component/" +psResourceName, UriKind.RelativeOrAbsolute);
return BitmapFrame.Create(oUri);
}
Learnings:
From my experiences the pack string is not the issue, check your streams and especially if reading it the first time has set the pointer to the end of the file and you need to re-set it to zero before reading again.
I hope this saves you the many hours I wish this piece had for me!
链接地址: http://www.djcxy.com/p/8904.html上一篇: 只有GUI属性返回到ViewModel
下一篇: WPF图像资源