开发者

How do you access to your image resources in MVVM WPF applications?

开发者 https://www.devze.com 2023-04-04 08:22 出处:网络
I have been integrating image resources to my WPF assemblies for quite a time, but I never really found a really p开发者_如何学编程retty way of binding them in my MVVM applications.

I have been integrating image resources to my WPF assemblies for quite a time, but I never really found a really p开发者_如何学编程retty way of binding them in my MVVM applications.

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

  • 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. 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();
       }
    }
    

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

  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}}" />
    

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消