对于一个WPF应用程序,它将需要10 - 20个小图标和图像用于说明目的,将它们作为嵌入式资源存储在程序集中是正确的方法吗?
如果是这样,我如何在XAML中指定图像控件应该从嵌入式资源加载图像?
对于一个WPF应用程序,它将需要10 - 20个小图标和图像用于说明目的,将它们作为嵌入式资源存储在程序集中是正确的方法吗?
如果是这样,我如何在XAML中指定图像控件应该从嵌入式资源加载图像?
当前回答
是的,这是正确的方法。
你可以在资源文件中使用图像,只使用路径:
<Image Source="..\Media\Image.png" />
您必须将映像文件的构建操作设置为“资源”。
其他回答
如果您正在使用Blend,为了使它更加简单,并且没有任何问题,为Source属性获取正确的路径,只需将图像从Project面板拖放到设计器上。
在代码中加载执行程序集中的资源,其中我的图像Freq.png位于Icons文件夹中,并定义为resource:
this.Icon = new BitmapImage(new Uri(@"pack://application:,,,/"
+ Assembly.GetExecutingAssembly().GetName().Name
+ ";component/"
+ "Icons/Freq.png", UriKind.Absolute));
我还做了一个函数:
/// <summary>
/// Load a resource WPF-BitmapImage (png, bmp, ...) from embedded resource defined as 'Resource' not as 'Embedded resource'.
/// </summary>
/// <param name="pathInApplication">Path without starting slash</param>
/// <param name="assembly">Usually 'Assembly.GetExecutingAssembly()'. If not mentionned, I will use the calling assembly</param>
/// <returns></returns>
public static BitmapImage LoadBitmapFromResource(string pathInApplication, Assembly assembly = null)
{
if (assembly == null)
{
assembly = Assembly.GetCallingAssembly();
}
if (pathInApplication[0] == '/')
{
pathInApplication = pathInApplication.Substring(1);
}
return new BitmapImage(new Uri(@"pack://application:,,,/" + assembly.GetName().Name + ";component/" + pathInApplication, UriKind.Absolute));
}
用法(假设将函数放在ResourceHelper类中):
this.Icon = ResourceHelper.LoadBitmapFromResource("Icons/Freq.png");
注意:请参见WPF中的MSDN包uri: Pack://application:…/ReferencedAssembly;component/Subfolder/ResourceFile.xaml
如何使用资源的完整描述:WPF应用程序资源,内容和数据文件
以及如何引用它们,请阅读“在WPF中打包uri”。
简而言之,甚至还有从被引用/引用程序集引用资源的方法。
下面工作和待设置的图像是在属性中的资源:
var bitmapSource = Imaging.CreateBitmapSourceFromHBitmap(MyProject.Properties.Resources.myImage.GetHbitmap(),
IntPtr.Zero,
Int32Rect.Empty,
BitmapSizeOptions.FromEmptyOptions());
MyButton.Background = new ImageBrush(bitmapSource);
img_username.Source = bitmapSource;
是的,这是正确的方法。
你可以在资源文件中使用图像,只使用路径:
<Image Source="..\Media\Image.png" />
您必须将映像文件的构建操作设置为“资源”。