1

is there a nice way to do the following. Get a WPF button and a Windows.Forms.ImageList and use them together. Here is the code:

    <Button Name="SOMETHING" Content="Button" Height="23" VerticalAlignment="Top" Width="75"/>

    System.Windows.Forms.ImageList imgList = new System.Windows.Forms.ImageList();

    string str_directory = System.IO.Path.GetDirectoryName(System.IO.Path.GetDirectoryName(System.IO.Directory.GetCurrentDirectory()));
    this.imgList.Images.Add(System.Drawing.Image.FromFile(str_directory + "\\Resources\\AboutImage.png"));
    WPFbutton.Background = imgList.Images[0];

I am tyring to get the Windows.Forms ImageList and use it on a WPF button. Is there a nice way to fix it?

  • 4
    Do not mix WPF and Windows Forms. It's not good idea. – General-Doomer May 08 '15 at 07:49
  • 1
    Choose for WPF or WinForms – Sybren May 08 '15 at 07:50
  • My first question would be why, and what is the advantage in your eyes to have your image as part of an ImageList. The example from @Clemens should help, but you could simply do it over XAML as well, your button can have a stackpanel containing and image and a text, or whatever you like (as long as you don't add the Content as a property, but rather as part of the button syntax, like: ``) – Icepickle May 08 '15 at 09:34

1 Answers1

1

There is no need for an ImageList. Just do it as shown in the code below, which assumes that the path "Resources\AboutImage.png" is relative to the application's current working directory.

Apparently you've called Path.GetDirectoryName two times to cut off the "bin\Debug\" or "bin\Release\" part of the path and thus access the image file directly from the Visual Studio project structure. This will not work when the application is deployed somewhere else. Instead, set the Build Action of the image file to Content, and Copy to Output Directory to Copy always or Copy if newer.

var path = Path.Combine(Directory.GetCurrentDirectory(), "Resources", "AboutImage.png");
var bitmap = new BitmapImage(new Uri(path));
WPFbutton.Background = new ImageBrush(bitmap);

However, a far better approach would be to load an image resource directly. Set the Build Action to Resource and load the image by a WPF Pack URI:

var bitmap = new BitmapImage(
    new Uri("pack://application:,,,/Resources/AboutImage.png"));
WPFbutton.Background = new ImageBrush(bitmap);

Besides that, you would usually set the Background in XAML, like:

<Button ...>
    <Button.Background>
        <ImageBrush ImageSource="/Resources/AboutImage.png"/>
    </Button.Background>
</Button>
Community
  • 1
  • 1
Clemens
  • 123,504
  • 12
  • 155
  • 268