Harry Boy
Harry Boy

Reputation: 4777

WPF cannot implicitly convert system.drawing.bitmap to media.brush

I want to change the background of a button manually in my WPF app.

I have an image imported into my resources and I want to do:

MyButton.Background = MyProject.Properties.Resources.myImage;

But I get the error:

cannot implicitly convert system.drawing.bitmap to media.brush

How can I do this??

Upvotes: 0

Views: 10720

Answers (2)

JleruOHeP
JleruOHeP

Reputation: 10386

You should read about brushes first here.

And then use ImageBrush, something like this:

MyButton.Background = new ImageBrush(...);

(or, maybe, put the brush into resources...)

UPDATE

You can find how to create imageSource from bitmap easilly. for example, here. Like:

var bitmapSource = Imaging.CreateBitmapSourceFromHBitmap(MyProject.Properties.Resources.myImage.GetHbitmap(),
                                  IntPtr.Zero,
                                  Int32Rect.Empty,
                                  BitmapSizeOptions.FromEmptyOptions());
MyButton.Background = new ImageBrush(bitmapSource);

Upvotes: 11

Clemens
Clemens

Reputation: 128147

In a WPF application, you do usually not add image resources as you did in WinForms.

Instead you add the image file directly to your Visual Studio project, just like any other file. If there are multiple images, it may make sense to put them in a subfolder of the project (e.g. called "images"). The Build Action of that file has to be set to Resource (which is the default for image files).

Now you can create a BitmapImage from a Pack URI to that file.

Finally you create an ImageBrush from the BitmapImage to set the Background property.

var uri = new Uri("pack://application:,,,/images/myImage.jpg");
var image = new BitmapImage(uri);
MyButton.Background = new ImageBrush(image);

Upvotes: 5

Related Questions