如何访问MVVM WPF应用程序中的图像资源?

问题描述:

我一直在将图像资源集成到我的WPF程序集中很长一段时间,但我从来没有真正找到一种在我的MVVM应用程序中绑定它们的方法。

I have been integrating image resources to my WPF assemblies for quite a time, but I never really found a really pretty way of binding them in my MVVM applications.

所以我想知道你们堆栈流用户是否可以在汇编资源中分享他们自己的做法:

So I was wondering if some you, * users, could share their own practice when it comes to assembly ressources:


  • 你如何引用它们在C#/ VB和XAML中?

  • 从代码中公开它们时,您公开了什么类型? (BitmapImage,Uri,string,...)

  • 您更喜欢从视图中引用它们还是通过视图模型绑定它们?

  • Do你使用特定的程序集来存储它们?你如何组织它们?

  • How do you reference them in C#/VB and XAML?
  • When exposing them from code, what type do you expose? (BitmapImage, Uri, string, ...)
  • Do you prefer referencing them from the view or binding them through view-model?
  • Do you use a specific assembly to store them? How do you organize them?

感谢您的帮助; - )

Thanks for your help ;-)

这就是我所做的......

This is what I do...


  1. 图像保存在某些文件夹中,例如图像。您可以将它们保存在任何程序集中。

  2. 单个图像的构建操作属性设置为资源 type。

  3. ViewModel将图像名称保存在 string 中(比如属性 MyImageName )当我绑定到来源时,我将其转换为相对路径 XAML中的对象...

  1. Images are kept in some folder such as Images in project's root folder. You can keep them in any assembly.
  2. Individual image has Build Action property set to Resource type.
  3. The ViewModel holds image name in string (say property MyImageName) and I convert it as a relative path when bound to the Source of Image object in XAML...

public class ImagePathConverter
{
   public void Convert(...)
   {
      return "pack://application:,,,/MyApplicationName;component/Images/" + value.ToString();
   }
}


其中 MyApplicationName 是短程序集的名称,其下面有 Images 文件夹。

where MyApplicationName is the short assembly's name that is having the Images folder under it.


  1. 在XAML中,假设视图模型实例绑定到整个视图的数据上下文和/或至少与图像的数据相关.... / p>

  1. In XAML, assuming the view model instance is bound to the data context of the entire view and / or atleast to the image's data contect ....

<Image Source="{Binding Path=MyImageName, Converter={StaticResource ImagePathConverter}}" />


但那是一个典型的方法通过MVVM引用WPF项目中的图像。其他方式包括加载Image的二进制流(来自 resx 内容类型图像或来自二进制数据库)。在这种情况下,您的转换器会将其转换为 BitMapImageSource

But then thats one of the typical ways to refer images in a WPF project via MVVM. Other ways include an Image's binary stream loaded (from resx or Content type images or from binary database). In such case your converter will convert it into a BitMapImageSource.