1

I've been looking for a better answer to my problem, and even when I solved it (not very elegantly) I would like to know if there's any other way. I've inherited a project I cannot modify too much, I mean, I can only add some other properties or override methods but not changing the base class or interface.

This project contains a class that inherits a WPF grid to modify certain aspects of the behavior. I have to add a new column (by code) with an image. Every single image is already stored into a Resource assembly and declared through static properties, for example, an icon I need is declared like this:

MyIcon.Source="{x:Static images:Common.Size_22.icon}"

I need to use this icon for my column and I tried every kind of declaration through a package and it didn't work. Finally I decided to embed this Bitmap sending it through a property:

<mygrid:MyGridControl Model="{Binding}" Refresh="{Binding Refresh}" 
CommentsImageSource="{x:Static images:Common.Size_22.icon}" />

When I create the image cell I have to also create an image object and set source using a conversion between Bitmap and BitmapImage

image.Source = ToBitmapSource((System.Drawing.Bitmap)CommentsImageSource);

It works but I'm very disappointed with this resolution, is there any better way to do it? I couldn't reference the source file to avoid sending a Bitmap by property.

1
  • It would be nice if you would accept my answer as the correct one. Thanks! Commented Dec 25, 2014 at 1:47

1 Answer 1

6

When you have the opportunity to assign the ImageSource in code, I use BitmapToBitmapSource(Resources.image_name) with

public static BitmapSource BitmapToBitmapSource(Bitmap bitmap)
{
  return Imaging.CreateBitmapSourceFromHBitmap(bitmap.GetHbitmap(), IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
}

This creates an BitmapSource which you then can assign as the ImageSource of your control.

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

2 Comments

Great answer, I'm still looking for more information about reducing the solution (not only this part). Thanks for your answer.
This solution copy the entire Bitmap to RAM and doesn't handle any kind of cache. This means that it'll be allocated each time you load the resource.

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.