且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-06-22 02:16:16

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

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.