Click here to Skip to main content
15,867,704 members
Articles / Desktop Programming / WPF

WPF Country Combobox

Rate me:
Please Sign up or sign in to vote.
4.62/5 (7 votes)
16 Apr 2011CPOL2 min read 64.7K   3.7K   16   15
This article will help you to create a country dropdown with the help of WPF concepts like WPF converters

Introduction

This article will help you to create a country combobox with country flags. You will be able to understand the capability of WPF converters while binding.

countrycombo.jpg

Background

The reader is assumed to be at least a beginner in WPF who knows the basics of data binding techniques, dependency properties, etc.

Using the Code

You first create a WPF usercontrol "countryDropdown" in which you place a WPF combobox. Bind country data from a dependency property. Add data template for the combobox in which it is divided into two parts; one is an image where flag image is shown and the other is the country name part which is a textblock.

Code for CountryDropdown.xaml

XML
<UserControl x:Class="Customcontrols.CountryDropdown" Name="ucCountryCombo"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:Convert="clr-namespace:Customcontrols.Converter" 
             mc:Ignorable="d" 
            Height="40" Width="200">
    <UserControl.Resources>
        <Convert:Converter x:Key="Converters"></Convert:Converter>
    </UserControl.Resources>
    <Grid>
        <ComboBox Name="CountryrCombo" 
    ItemsSource="{Binding ElementName=ucCountryCombo, Path=Countries}" 
	SelectedValuePath="code"  SelectedValue="{Binding ElementName=ucCountryCombo, 
	Path=SelectedCountry}" >
            <ComboBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Horizontal">
                        <Image Width="20" Height="20" Margin="5" 
			Source="{Binding code, 
			Converter={StaticResource Converters}}"/>
                        <TextBlock Margin="5" Text="{Binding country_Text}"/>
                    </StackPanel>
                </DataTemplate>
            </ComboBox.ItemTemplate>
        </ComboBox>
    </Grid>
</UserControl>

Two dependency properties are being created in the CS file.

Countries property is used to load the whole country names and SelectedCountry property is used for setting the selected country from the list.

In this combobox control, the country data is stored in an XML file in which you have a list of all countries till date along with their ISO country codes. You can download the country XML from here. We can either directly read XML data into a dataset using built-in function or you can use LINQ to XML for reading the data.

Code for CountryDropdown.xaml.cs

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Data;

namespace Customcontrols
{
    /// <summary>
    /// Interaction logic for CountryDropdown.xaml
    /// </summary>
    public partial class CountryDropdown : UserControl
    {
        public CountryDropdown()
        {
            InitializeComponent();
            Countries = GetData();
        }
        public DataTable Countries
        {
            get { return (DataTable)GetValue(CountriesProperty); }
            set { SetValue(CountriesProperty, value); }
        }
        
        public static readonly DependencyProperty CountriesProperty =
            DependencyProperty.Register("Countries", 
	   typeof(DataTable), typeof(CountryDropdown), new UIPropertyMetadata(null));

        public String SelectedCountry
        {
            get { return (String)GetValue(SelectedCountryProperty); }
            set { SetValue(SelectedCountryProperty, value); }
        }
     
        public static readonly DependencyProperty SelectedCountryProperty =
            DependencyProperty.Register("SelectedCountry", 
	   typeof(String), typeof(CountryDropdown), new UIPropertyMetadata(null));

        public DataTable  GetData()
        {
            DataTable dt = new DataTable();

            DataSet ds = new DataSet();

            ds.ReadXml(AppDomain.CurrentDomain.BaseDirectory + "XML\\countries.xml");
            return ds.Tables[0];
        }
    }
}

Thus, we get a combo box having a datasource as a datatable which contains the whole country names and their associated ISO country codes. The next thing in this control is the associated flags. The flags icons can be downloaded from here. We get a list of icons whose file name is ISO code + extension. So the trick here is for each country data in the combobox we have an associated country code in the data source, so we can convert this ISO code to image source and bind to an image in the data template of combobox.

Code for converter.cs

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Data;
using System.Globalization;

namespace Customcontrols.Converter
{
    public class Converter : IValueConverter
    {
        public object Convert(object value, Type targetType,
        object parameter, CultureInfo culture)
        {
            string urImage = AppDomain.CurrentDomain.BaseDirectory + 
			"Images\\Countries\\"+ value.ToString() + ".png";
            return urImage;
        }

        public object ConvertBack(object value, Type targetType,
            object parameter, CultureInfo culture)
        {
            return null;
        }
    }
} 

In the XAML, we can bind this converter for the image data. Thus, at run time, it automatically converts the ISO code to image source.

History

  • 17th April, 2011: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) NeST
India India
Professional: Have 5 years experience in ASP.Net,C#.Net,MVC,WPF,,Entity Framework,WCF,LINQ,JQuery,JQuery Mobile,MS SQL,Oracle,Silverlight,MS CRM,Dynamics GP

Academics : BTech in Computer Science and Engineering from Mar Athanasius College of Engineering,Kothamangalam,Kerala .

Location : Kothamangalam, Ernakulam ,Kerala ,India
Presently working at Technopark Trivandrum,
Mob: 8281065563

Comments and Discussions

 
QuestionSelectItem Pin
Member 1295270128-Feb-17 8:43
Member 1295270128-Feb-17 8:43 
QuestionPlease correct runtime errors! Pin
Manish Dubeyy6-Jul-16 3:20
Manish Dubeyy6-Jul-16 3:20 
GeneralMy vote of 5 Pin
Pr!y@4-Feb-12 3:50
Pr!y@4-Feb-12 3:50 
Questionnice - is this convertible into Silverlight 4? Pin
Greg Hazz9-Aug-11 6:55
Greg Hazz9-Aug-11 6:55 
GeneralSource Code no Images Pin
soltec24-May-11 10:39
soltec24-May-11 10:39 
GeneralWhy not just use XmlDataProvider instead Pin
Sacha Barber18-Apr-11 21:37
Sacha Barber18-Apr-11 21:37 
GeneralRe: Why not just use XmlDataProvider instead Pin
sudheer muhammed18-Apr-11 21:52
sudheer muhammed18-Apr-11 21:52 
GeneralRe: Why not just use XmlDataProvider instead Pin
Sacha Barber18-Apr-11 21:57
Sacha Barber18-Apr-11 21:57 
GeneralRe: Why not just use XmlDataProvider instead Pin
RAND 45586618-Apr-11 23:32
RAND 45586618-Apr-11 23:32 
"Less heavy than DataTable"

What about MSDN: XmlDataProvider fails when it does not have permissions to access the given data ?
Rand

GeneralRe: Why not just use XmlDataProvider instead Pin
sudheer muhammed19-Apr-11 0:07
sudheer muhammed19-Apr-11 0:07 
GeneralRe: Why not just use XmlDataProvider instead Pin
Sacha Barber20-Apr-11 0:14
Sacha Barber20-Apr-11 0:14 
GeneralRe: Why not just use XmlDataProvider instead Pin
sudheer muhammed20-Apr-11 1:50
sudheer muhammed20-Apr-11 1:50 
GeneralRe: Why not just use XmlDataProvider instead Pin
Sacha Barber20-Apr-11 2:07
Sacha Barber20-Apr-11 2:07 
GeneralRe: Why not just use XmlDataProvider instead Pin
Sacha Barber19-Apr-11 0:11
Sacha Barber19-Apr-11 0:11 
GeneralRe: Why not just use XmlDataProvider instead Pin
sudheer muhammed19-Apr-11 0:03
sudheer muhammed19-Apr-11 0:03 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.