Tuesday, October 14, 2008

MSDN Question on WPF: How do I set Window.Icon Property?

Today, I came across a post on MSDN forums where one of the members was not able to set Icon property from C#. Turns out Window.Icon is a dependency property and is of type "ImageSource".

Anyway, given a System.Drawing.Image, you could use the following method to obtain the ImageSource.
public static ImageSource FromImage(System.Drawing.Image image)
{
            MemoryStream ms = new MemoryStream();
            image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
            return BitmapFrame.Create(ms);
}

You could set the icon using the method, as shown below.
this.Icon = FromImage(System.Drawing.Image.FromFile("Creek.jpg"));

There might definitely be a better way to do that, but it works (might not be faster).

So, if you directly want to set Creek.jpg as Window icon(from code), you could do this.
Uri iconUri = new Uri("Creek.JPG", UriKind.RelativeOrAbsolute);
.Icon = BitmapFrame.Create(iconUri);
 

No comments: