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

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. <Grid>
  11. <DockPanel>
  12. <Grid>
  13. <Grid.RowDefinitions>
  14. <RowDefinition Height="0.05*" />
  15. <RowDefinition Height="*" />
  16. <RowDefinition Height="0.05*" />
  17. </Grid.RowDefinitions>
  18. <Border Grid.Row="1"
  19. Width=" 400"
  20. Height="300"
  21. BorderThickness="1"
  22. BorderBrush="Black"
  23. CornerRadius="20"
  24. Opacity="1">
  25. <Border.Background>
  26. <ImageBrush ImageSource="/Data Binding using File;component/Content/img/bg_2.png">
  27. <ImageBrush.RelativeTransform>
  28. <TransformGroup>
  29. <ScaleTransform CenterY="0.5" CenterX="0.5" ScaleX="1.5" ScaleY="1.5"/>
  30. <SkewTransform CenterY="0.5" CenterX="0.5"/>
  31. <RotateTransform CenterY="0.5" CenterX="0.5"/>
  32. <TranslateTransform/>
  33. </TransformGroup>
  34. </ImageBrush.RelativeTransform>
  35. </ImageBrush>
  36. </Border.Background>
  37. <StackPanel Orientation="Vertical"
  38. HorizontalAlignment="Center"
  39. VerticalAlignment="Center"
  40. Width=" 400"
  41. Height="300" >
  42. <Border Width="220"
  43. Height="50"
  44. Margin="0,120,0,0">
  45. <Border.Background>
  46. <ImageBrush ImageSource="/Data Binding using File;component/Content/img/text-box_bg.png"/>
  47. </Border.Background>
  48. <ComboBox x:Name="cmbCountryList"
  49. Width="220"
  50. Height="50"
  51. FontSize="18"
  52. HorizontalAlignment="Center"
  53. VerticalAlignment="Top"
  54. BorderThickness="0"
  55. VerticalContentAlignment="Center"
  56. Padding="15,0,0,0"
  57. Background="Transparent"
  58. Foreground="Black"
  59. IsEditable="True"
  60. Margin="0"/>
  61. </Border>
  62. </StackPanel>
  63. </Border>
  64. </Grid>
  65. </DockPanel>
  66. </Grid>
  67. </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. namespace Data_Binding_using_File.Views
  17. {
  18. /// <summary>
  19. /// Interaction logic for HomePage.xaml
  20. /// </summary>
  21. public partial class HomePage : Page
  22. {
  23. public HomePage()
  24. {
  25. InitializeComponent();
  26. this.Loaded += HomePage_Loaded;
  27. }
  28. private void HomePage_Loaded(object sender, RoutedEventArgs e)
  29. {
  30. try
  31. {
  32. // Binding
  33. this.cmbCountryList.DisplayMemberPath = "CountryName";
  34. this.cmbCountryList.SelectedValuePath = "CountryCode";
  35. this.cmbCountryList.ItemsSource = HomeBusinessLogic.LoadCountryList();
  36. this.cmbCountryList.Text = "Choose Country";
  37. }
  38. catch (Exception ex)
  39. {
  40. Console.Write(ex);
  41. }
  42. }
  43. }
  44. }

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. namespace Data_Binding_using_File
  16. {
  17. /// <summary>
  18. /// Interaction logic for MainWindow.xaml
  19. /// </summary>
  20. public partial class MainWindow : Window
  21. {
  22. public MainWindow()
  23. {
  24. InitializeComponent();
  25. this.Loaded += MainWindow_Loaded;
  26. }
  27. private void MainWindow_Loaded(object sender, RoutedEventArgs e)
  28. {
  29. this.mainFrame.Navigate(new Uri("/Views/HomePage.xaml", UriKind.Relative));
  30. }
  31. }
  32. }

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.