0

I'm trying to set a backgroundpicture for my button in my code behind. The picture is available as a png in the resources.

Button sampleBody = new Button();
ImageBrush imageBrush = new ImageBrush((ImageSource)Properties.Resources.MyPic);
imageBrush.Stretch = Stretch.Fill;

sampleBody.Background = imageBrush;

The above code isn't working (obviously) but that's what I'm trying todo in a nutshell.

Thanks in advance for any tips.

Clemens
  • 123,504
  • 12
  • 155
  • 268
  • Button Content property can be used to display an image, – PJRobot Jan 16 '19 at 13:38
  • 1
    WPF uses image resources in a different way. Do not add an image to Resources.resx. Instead, just add an image file to the Visual Studio project and load it via a Resource File Pack URI: `new ImageBrush(new BitmapImage(new Uri("pack://application:,,,/Resources/mypic.png")));` – Clemens Jan 16 '19 at 13:53
  • @Clemens Thanks for the answer. The real question is that I have a bitmap class property that I want to use as a backgroundimage. I wanted to use resources just for testing. So I need a way to do this without URIs. – Stephan Pillhofer Jan 16 '19 at 13:57
  • 1
    While this is not the typical way to use an image resource in WPF, you may of course just convert from Bitmap to ImageSource. Just search StackOverflow, there are a couple of solutions. Either encode the Bitmap to a MemoryStream, from which you decode a BitmapImage or BitmapFrame, or use `Imaging.CreateBitmapSourceFromHBitmap`. – Clemens Jan 16 '19 at 14:02
  • Ok, I will try to implement this. Because you said this isn't a typical way to use image resources in WPF: My app has various diffrent components which all have a different image. The user can create new elements and load them as an extension into the program. How could this work if I want to manage all components in an internal list? Do you have a tipp for me? – Stephan Pillhofer Jan 16 '19 at 14:11
  • An assembly resource file shouldn't be handled any different than a bitmap resource in Resources.resx. It is located in an assembly, but can be accessed from other assemblies. Pack URIs can contain referenced assembly names: https://learn.microsoft.com/en-us/dotnet/framework/wpf/app-development/pack-uris-in-wpf#resource-file-pack-uris – Clemens Jan 16 '19 at 14:36
  • Kay, thx :) `Imaging.CreateBitmapSourceFromHBitmap` also worked perfectly. – Stephan Pillhofer Jan 16 '19 at 15:12

0 Answers0