WPF - Dropdown Menu/Combobox Menu Data Binding Using Text File

One of the key concepts in WPF development is data binding. While one of the commonly utilized UI controls of WPF is a dropdown menu or combo box menu for better user interactivity, the Data Binding concept revolves around binding of the data from sources like text files or database to UI control. In WPF, data binding is two way as it follows MVVM design pattern.

Today, I shall be demonstrating implementation of data binding using a text file with the dropdown menu or the combobox menu. Remember in WPF drop-down menu is known as a combobox menu.

 
Prerequisites

 

Following are some prerequisites before you proceed further in this tutorial,

  1. Knowledge of Windows Presentation Form (WPF).
  2. Knowledge of C# programming.
  3. Knowledge of C# LINQ.

You can download the complete source code for this tutorial or you can follow the step by step discussion below. The sample code is developed in Microsoft Visual Studio 2015 Enterprise.

Let's begin now.

Step 1

Create a new WPF application project and name it "Data Binding using File".

Step 2

Import "Content\files\country_list.txt" file into your project and then set "Build Action" & "Copy to Output Directory" properties of the file as shown below i.e.




 

Step 3

Now, create "Helper_Code\Objects\CountryObj.cs" file and replace following code in it i.e.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading.Tasks;  
  6.   
  7. namespace Data_Binding_using_File.Helper_Code.Objects  
  8. {  
  9.     public class CountryObj  
  10.     {  
  11.         public string CountryCode { getset; }  
  12.         public string CountryName { getset; }  
  13.     }  

In the above code, I have created an object which will load our data from the file in a list then bind that data with the dropdown menu or combobox menu.

Step 4

Create "Model\BusinessLogic\HomeBusinessLogic.cs" file and replace following code in it i.e.

  1. using Data_Binding_using_File.Helper_Code.Objects;  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.IO;  
  5. using System.Linq;  
  6. using System.Reflection;  
  7. using System.Text;  
  8. using System.Threading.Tasks;  
  9.   
  10. namespace Data_Binding_using_File.Model.BusinessLogic.Helper_Code.Common  
  11. {  
  12.     public class HomeBusinessLogic  
  13.     {  
  14.         public static List<CountryObj> LoadCountryList()  
  15.         {  
  16.             // Initialization  
  17.             List<CountryObj> lst = new List<CountryObj>();  
  18.             string line = string.Empty;  
  19.   
  20.             try  
  21.             {  
  22.                 // Initialization  
  23.                 string srcFilePath = "Content/files/country_list.txt";  
  24.                 string rootPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase);  
  25.                 string fullPath = Path.Combine(rootPath, srcFilePath);  
  26.                 string filePath = new Uri(fullPath).LocalPath;  
  27.   
  28.                 StreamReader sr = new StreamReader(new FileStream(filePath, FileMode.Open, FileAccess.Read));  
  29.   
  30.                 // Read file.  
  31.                 while ((line = sr.ReadLine()) != null)  
  32.                 {  
  33.                     // Initialization.  
  34.                     CountryObj obj = new CountryObj();  
  35.                     string[] info = line.Split(':');  
  36.   
  37.                     // Setting.  
  38.                     obj.CountryCode = info[0].ToString();  
  39.                     obj.CountryName = info[1].ToString();  
  40.   
  41.                     // Adding.  
  42.                     lst.Add(obj);  
  43.                 }  
  44.   
  45.                 // Closing.  
  46.                 sr.Dispose();  
  47.                 sr.Close();  
  48.             }  
  49.             catch (Exception ex)  
  50.             {  
  51.                 throw ex;  
  52.             }  
  53.   
  54.             return lst;  
  55.         }  
  56.     }  

In the above code, I have developed the business logic for the method "LoadCountryList()", which will load the data from text file into the main memory as a list of object "CountryObj".

Step 5

Now, create a new page "Views\HomePage.xaml" file and replace the following code in it i.e.

  1. <Page x:Class="Data_Binding_using_File.Views.HomePage"  
  2.       xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"  
  3.       xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"  
  4.       xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"   
  5.       xmlns:d="http://schemas.microsoft.com/expression/blend/2008"   
  6.       xmlns:local="clr-namespace:Data_Binding_using_File.Views"  
  7.       mc:Ignorable="d"   
  8.       d:DesignHeight="480" d:DesignWidth="640"  
  9.       Title="Home Page">  
  10.   
  11.     <Grid>  
  12.         <DockPanel>  
  13.             <Grid>  
  14.                 <Grid.RowDefinitions>  
  15.                     <RowDefinition Height="0.05*" />  
  16.                     <RowDefinition Height="*" />  
  17.                     <RowDefinition Height="0.05*" />  
  18.                 </Grid.RowDefinitions>  
  19.   
  20.                 <Border Grid.Row="1"  
  21.                         Width=" 400"  
  22.                         Height="300"   
  23.                         BorderThickness="1"   
  24.                         BorderBrush="Black"   
  25.                         CornerRadius="20"   
  26.                         Opacity="1">  
  27.                     <Border.Background>  
  28.                         <ImageBrush ImageSource="/Data Binding using File;component/Content/img/bg_2.png">  
  29.                             <ImageBrush.RelativeTransform>  
  30.                                 <TransformGroup>  
  31.                                     <ScaleTransform CenterY="0.5" CenterX="0.5" ScaleX="1.5" ScaleY="1.5"/>  
  32.                                     <SkewTransform CenterY="0.5" CenterX="0.5"/>  
  33.                                     <RotateTransform CenterY="0.5" CenterX="0.5"/>  
  34.                                     <TranslateTransform/>  
  35.                                 </TransformGroup>  
  36.                             </ImageBrush.RelativeTransform>  
  37.                         </ImageBrush>  
  38.                     </Border.Background>  
  39.   
  40.                     <StackPanel Orientation="Vertical"   
  41.                                 HorizontalAlignment="Center"  
  42.                                 VerticalAlignment="Center"  
  43.                                 Width=" 400"  
  44.                                 Height="300" >  
  45.   
  46.                         <Border Width="220"  
  47.                                 Height="50"  
  48.                                 Margin="0,120,0,0">  
  49.   
  50.                             <Border.Background>  
  51.                                 <ImageBrush ImageSource="/Data Binding using File;component/Content/img/text-box_bg.png"/>  
  52.                             </Border.Background>  
  53.   
  54.                             <ComboBox x:Name="cmbCountryList"   
  55.                                     Width="220"   
  56.                                     Height="50"  
  57.                                     FontSize="18"    
  58.                                     HorizontalAlignment="Center"   
  59.                                     VerticalAlignment="Top"  
  60.                                     BorderThickness="0"  
  61.                                     VerticalContentAlignment="Center"  
  62.                                     Padding="15,0,0,0"   
  63.                                     Background="Transparent"  
  64.                                     Foreground="Black"  
  65.                                     IsEditable="True"   
  66.                                     Margin="0"/>  
  67.                         </Border>  
  68.   
  69.                     </StackPanel>  
  70.                 </Border>  
  71.             </Grid>  
  72.   
  73.         </DockPanel>  
  74.     </Grid>  
  75. </Page> 

In the above code, I have added a simple dropdown menu/combobox menu UI control with "IsEditable" property enabled, in order to make dropdown menu/combobox menu search.

Step 6

Open the "Views\HomePage.xaml\HomePage.xaml.cs" file and replace following code in it i.e.

  1. using Data_Binding_using_File.Model.BusinessLogic.Helper_Code.Common;  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.Linq;  
  5. using System.Text;  
  6. using System.Threading.Tasks;  
  7. using System.Windows;  
  8. using System.Windows.Controls;  
  9. using System.Windows.Data;  
  10. using System.Windows.Documents;  
  11. using System.Windows.Input;  
  12. using System.Windows.Media;  
  13. using System.Windows.Media.Imaging;  
  14. using System.Windows.Navigation;  
  15. using System.Windows.Shapes;  
  16.   
  17. namespace Data_Binding_using_File.Views  
  18. {  
  19.     /// <summary>  
  20.     /// Interaction logic for HomePage.xaml  
  21.     /// </summary>  
  22.     public partial class HomePage : Page  
  23.     {  
  24.         public HomePage()  
  25.         {  
  26.             InitializeComponent();  
  27.   
  28.             this.Loaded += HomePage_Loaded;  
  29.         }  
  30.   
  31.         private void HomePage_Loaded(object sender, RoutedEventArgs e)  
  32.         {  
  33.             try  
  34.             {  
  35.                 // Binding  
  36.                 this.cmbCountryList.DisplayMemberPath = "CountryName";  
  37.                 this.cmbCountryList.SelectedValuePath = "CountryCode";  
  38.                 this.cmbCountryList.ItemsSource = HomeBusinessLogic.LoadCountryList();  
  39.                 this.cmbCountryList.Text = "Choose Country";  
  40.             }  
  41.             catch (Exception ex)  
  42.             {  
  43.                 Console.Write(ex);  
  44.             }  
  45.         }  
  46.     }  

In the above code, I have binned the data from text file with the dropdown menu/combobox menu. The "DisplayMemberPath" property will display the names of the country and "SelectedValuePath" property will have corresponding country code value.

Step 7

We need to attach the page inside the main window so, open the "MainWindow.xaml" file and replace following in it i.e.

  1. <Window x:Class="Data_Binding_using_File.MainWindow"  
  2.         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"  
  3.         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"  
  4.         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"  
  5.         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"  
  6.         xmlns:local="clr-namespace:Data_Binding_using_File"  
  7.         mc:Ignorable="d"  
  8.         Title="WPF - Dropdown Menu/Combobox Menu Data Binding using Text File"  
  9.         d:DesignHeight="480" d:DesignWidth="640">  
  10.     <Grid>  
  11.         <Grid.Background>  
  12.             <ImageBrush ImageSource="Content/img/main_bg.jpg"/>  
  13.         </Grid.Background>  
  14.         <Frame x:Name="mainFrame"   
  15.                NavigationUIVisibility="Hidden"/>  
  16.     </Grid>  
  17. </Window> 

In the above code, I have added a default background image taken from freepike and a frame which will contain my page and window will immediately navigate to the main page.

Step 8

Open the "MainWindow.xaml\MainWindow.cs" file and replace the following code in it i.e.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading.Tasks;  
  6. using System.Windows;  
  7. using System.Windows.Controls;  
  8. using System.Windows.Data;  
  9. using System.Windows.Documents;  
  10. using System.Windows.Input;  
  11. using System.Windows.Media;  
  12. using System.Windows.Media.Imaging;  
  13. using System.Windows.Navigation;  
  14. using System.Windows.Shapes;  
  15.   
  16. namespace Data_Binding_using_File  
  17. {  
  18.     /// <summary>  
  19.     /// Interaction logic for MainWindow.xaml  
  20.     /// </summary>  
  21.     public partial class MainWindow : Window  
  22.     {  
  23.         public MainWindow()  
  24.         {  
  25.             InitializeComponent();  
  26.   
  27.             this.Loaded += MainWindow_Loaded;  
  28.         }  
  29.   
  30.         private void MainWindow_Loaded(object sender, RoutedEventArgs e)  
  31.         {  
  32.             this.mainFrame.Navigate(new Uri("/Views/HomePage.xaml", UriKind.Relative));  
  33.         }  
  34.     }  

The above piece of code will navigate the frame to our main page when the window is launched.

Step 9

Execute the project and you will be able to see following i.e.




Conclusion

 

In this article, learned to create WPF dropdown menu UI control formally know as combobox menu UI control in WPF. You also learned to bind data from text file to the dropdown menu.comboboc menu UI control in WPF application. You learned to add background to the main window and you learned to add pages within the window by using frame control.

Disclaimer

The background image used in this article has been taken from freepike.