Windows Icon In WPF

An Icon is a bitmap image (.ico file) that is displayed in the top left corner of a Window. Visual Studio designer allows you to create your own icon images. To add an icon to a project, right click on the project name in Solution Explorer. Right click will open Add Items menu. Select Add >> New Item.

Now on Installed Templates, select Icon File (see Figure 1) and click Add. This action adds Icon1.ico file and opens the image editor.

Windows Icon In WPF
Figure 1

In the image editor (see Figure 2), you design your icon the way you like. There are two icon sizes available in the editor - 16x16 and 32x32.

 Windows Icon In WPF
Figure 2

The Icon attribute of Window is used to set Icon of a window. Listing 1 sets Icon1.ico file as icon of Window.

  1. <Window x:Class="WindowSample.MainWindow"  
  2.     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"  
  3.     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"  
  4.     Title="WPF Window Sample" Height="350" Width="525"  
  5.  Name="FirstWindow" Icon="Icon1.ico" >  

Listing 1

The output with new icon looks like Figure 3.

Windows Icon In WPF
Figure 3

The Icon property of Window class represents a window's icon at run-time. This property takes an ImageSource variable.

The following code snippet uses BitmapFrame.Create method to create an ImageSource and sets the Icon property of a Window.

  1. Uri iconUri = newUri("pack://application:,,,/Icon1.ico", UriKind.RelativeOrAbsolute);  
  2. this.Icon = BitmapFrame.Create(iconUri);  

Summary

In this article, I demonstrated how to use Icon property of a Window to load an icon in a WPF application.


Mindcracker
Founded in 2003, Mindcracker is the authority in custom software development and innovation. We put best practices into action. We deliver solutions based on consumer and industry analysis.