Image: Several CountryFlag controls in action
CountryFlag control is a
UserControl that allows you to display the flag of a particular country, in your WPF application, from a choice of 223 countries. This article describes how to use the control and how I went about creating it. The control will hopefully save you from having to scour the net for flag images and from writing numerous lines of code to implement the functionality it provides.
In order to use the control, add a reference to CountryFlag.dll in your project. In Expression Blend, make the Assets panel active and start typing the word '
CountryFlag' in the Search box. The
CountryFlag control should be displayed as you continue typing.
Double-click on the control to add it to your application or select it and draw out the control in your application window.
With the control you've just added still selected, look for the
Flag property in the Miscellaneous section of the Properties panel.
Expand the combobox and select the country whose flag you want to display.
Once you select a country, its flag should be displayed in the control.
Specifying a Flag in Code
You can also specify which flag you want to display using code.
Private Function ShowFlag() As String
CountryFlagCtrl.Flag = Country.Kenya
Dim countryFlg As String = CountryFlagCtrl.Flag.ToString
private string ShowFlag()
CountryFlagCtrl.Flag = Country.Kenya;
string countryFlg = CountryFlagCtrl.Flag.ToString();
Once you type the equal sign IntelliSense should help you along:
Design and Layout
The control contains a single Layout control and an
Image control named
UserControl library contains an enumeration,
Country, that contains the names of 223 countries. Here's parts of the
Public Enum Country
UserControl class contains code for creating a
DependencyProperty of type
Public Property Flag() As Country
Return CType(GetValue(FlagProperty), Country)
Set(ByVal value As Country)
Public Shared FlagProperty As DependencyProperty = _
New FrameworkPropertyMetadata( _
New PropertyChangedCallback(AddressOf ChangeFlag)))
Private Shared Sub ChangeFlag(ByVal source As DependencyObject, _
ByVal e As DependencyPropertyChangedEventArgs)
Dim countryName As String = CType(e.NewValue, Country).ToString
Dim path As String = "flags/" & countryname & ".png"
CType(source, CountryFlag).FlagImage.Source = _
New BitmapImage(New Uri(path, UriKind.Relative))
Notice that in the callback method,
ChangeFlag, we specify the image for the control's
Image control. The reason the .dll does not need to come bundled with a separate folder containing image files is because the images are embedded in the assembly. If you look in the Solution Explorer of Visual Studio, you will notice a folder named Flags that contains the image files.
CountryFlag will hopefully prove to be useful and I hope you gained more than that from reading the article. Cheers!
- 3rd May, 2011: Initial post