user3072882
user3072882

Reputation: 75

WPF button using System.Windows.Forms.ImageList

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?

Upvotes: 1

Views: 505

Answers (1)

Clemens
Clemens

Reputation: 128157

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>

Upvotes: 2

Related Questions