1

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, 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 ;-)

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Not the best practice :). I would rather create some enum on viewmodel representing each image type and wrote converter for converting type to image. Much more code, but much better maintability and testability.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.