ComboBox Binding in MVVM
WPF Developers can easily bind One value to the combobox but however binding two values in Combobox is a matter of some confusion.
So today I am going to show you an example in which I am adding two values ‘Country Code’ and ‘Country Name’ to a combobox. Here I am following MVVM Pattern. And After reading this post hope you will also realise the importance of DataTemplate.
Screenshot of the Output what we are going to build
Create a new WPF Solution name it – ComboBoxBinding. And Add 2 Class Files name them ModelCountry.cs and ViewModelCountry.cs
public class ViewModelCountry { private ObservableCollection countryLst; public ObservableCollection CountryLst { get { return countryLst; } set { countryLst = value; } } public ViewModelCountry() { CountryLst = new ObservableCollection() { new ModelCountry() { Country_Code=”IN”,Country_Name=”India” }, new ModelCountry() { Country_Code=”US”,Country_Name=”America” }, new ModelCountry() { Country_Code=”DE”,Country_Name=”Germany” }, new ModelCountry() { Country_Code=”AU”,Country_Name=”Australia” }, new ModelCountry() { Country_Code=”BE”,Country_Name=”Belgium” }, new ModelCountry() { Country_Code=”FR”,Country_Name=”France” }, }; } }
public class ModelCountry { private string country_Code; public string Country_Code { get { return country_Code; } set { country_Code = value; } } private string country_Name; public string Country_Name { get { return country_Name; } set { country_Name = value; } } }
<Window x:Class="ComboBoxBinding.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:vm="clr-namespace:ComboBoxBinding" Title="ComboBox Demo" Height="350" Width="525"> <Window.DataContext> <vm:ViewModelCountry></vm:ViewModelCountry> </Window.DataContext> <Grid Background="#98dafc"> <StackPanel> <TextBlock Text="Normal Binding" Width="200" Height="30" FontStyle="Italic" FontWeight="Bold" FontSize="20" /> <ComboBox x:Name="comCountry" Width="300" Height="40" SelectedIndex="0" ItemsSource="{Binding CountryLst}" SelectedItem="{Binding Country_Code}" DisplayMemberPath="Country_Name" /> <TextBlock Text="Both Id and Name Binding" Width="260" Height="30" FontStyle="Italic" FontWeight="Bold" FontSize="20" /> <ComboBox x:Name="comCCountry" ItemsSource="{Binding CountryLst}" Width="300" Height="40" SelectedIndex="0"> <ComboBox.ItemTemplate> <DataTemplate> <StackPanel Orientation="Horizontal"> <TextBlock Text="{Binding Country_Code}"/> <TextBlock Text=" – "/> <TextBlock Text="{Binding Country_Name}"/> </StackPanel> </DataTemplate> </ComboBox.ItemTemplate> </ComboBox> </StackPanel> </Grid> </Window>
Output – Expanding ComboBox with one value bind
Output – Expanding ComboBox with two values bind