Header Ads

WPF: Dropdown Menu/Combobox Menu Data Binding using Text File

One of the key concept in WPF development is data binding. While one of the commonly utilize UI control of WPF is dropdown menu or combobox menu for better user interactivity. Data binding concept revolves around binding of 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 text file with dropdown menu or combobox menu. Remember in WPF dropdown menu is known as combobox menu.


Prerequisites:

Following are some prerequisites before you proceed further in this tutorial:
  1. Knowledge about Windows Presentation Form (WPF).
  2. Knowledge about C# programming.
  3. Knowledge about 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.

Download Link

Let's begin now.

1) Create a new WPF application project and name it "Data Binding using File".
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.


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

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Data_Binding_using_File.Helper_Code.Objects
{
    public class CountryObj
    {
        public string CountryCode { get; set; }
        public string CountryName { get; set; }
    }
}

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.

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

using Data_Binding_using_File.Helper_Code.Objects;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace Data_Binding_using_File.Model.BusinessLogic.Helper_Code.Common
{
    public class HomeBusinessLogic
    {
        public static List<CountryObj> LoadCountryList()
        {
            // Initialization
            List<CountryObj> lst = new List<CountryObj>();
            string line = string.Empty;

            try
            {
                // Initialization
                string srcFilePath = "Content/files/country_list.txt";
                string rootPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase);
                string fullPath = Path.Combine(rootPath, srcFilePath);
                string filePath = new Uri(fullPath).LocalPath;

                StreamReader sr = new StreamReader(new FileStream(filePath, FileMode.Open, FileAccess.Read));

                // Read file.
                while ((line = sr.ReadLine()) != null)
                {
                    // Initialization.
                    CountryObj obj = new CountryObj();
                    string[] info = line.Split(':');

                    // Setting.
                    obj.CountryCode = info[0].ToString();
                    obj.CountryName = info[1].ToString();

                    // Adding.
                    lst.Add(obj);
                }

                // Closing.
                sr.Dispose();
                sr.Close();
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return lst;
        }
    }
}

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".

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

<Page x:Class="Data_Binding_using_File.Views.HomePage"
      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:local="clr-namespace:Data_Binding_using_File.Views"
      mc:Ignorable="d" 
      d:DesignHeight="480" d:DesignWidth="640"
      Title="Home Page">

    <Grid>
        <DockPanel>
            <Grid>
                <Grid.RowDefinitions>
                    <RowDefinition Height="0.05*" />
                    <RowDefinition Height="*" />
                    <RowDefinition Height="0.05*" />
                </Grid.RowDefinitions>

                <Border Grid.Row="1"
                        Width=" 400"
                        Height="300" 
                        BorderThickness="1" 
                        BorderBrush="Black" 
                        CornerRadius="20" 
                        Opacity="1">
                    <Border.Background>
                        <ImageBrush ImageSource="/Data Binding using File;component/Content/img/bg_2.png">
                            <ImageBrush.RelativeTransform>
                                <TransformGroup>
                                    <ScaleTransform CenterY="0.5" CenterX="0.5" ScaleX="1.5" ScaleY="1.5"/>
                                    <SkewTransform CenterY="0.5" CenterX="0.5"/>
                                    <RotateTransform CenterY="0.5" CenterX="0.5"/>
                                    <TranslateTransform/>
                                </TransformGroup>
                            </ImageBrush.RelativeTransform>
                        </ImageBrush>
                    </Border.Background>

                    <StackPanel Orientation="Vertical" 
                                HorizontalAlignment="Center"
                                VerticalAlignment="Center"
                                Width=" 400"
                                Height="300" >

                        <Border Width="220"
                                Height="50"
                                Margin="0,120,0,0">

                            <Border.Background>
                                <ImageBrush ImageSource="/Data Binding using File;component/Content/img/text-box_bg.png"/>
                            </Border.Background>

                            <ComboBox x:Name="cmbCountryList" 
                                    Width="220" 
                                    Height="50"
                                    FontSize="18"  
                                    HorizontalAlignment="Center" 
                                    VerticalAlignment="Top"
                                    BorderThickness="0"
                                    VerticalContentAlignment="Center"
                                    Padding="15,0,0,0" 
                                    Background="Transparent"
                                    Foreground="Black"
                                    IsEditable="True" 
                                    Margin="0"/>
                        </Border>

                    </StackPanel>
                </Border>
            </Grid>

        </DockPanel>
    </Grid>
</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.

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

using Data_Binding_using_File.Model.BusinessLogic.Helper_Code.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
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;

namespace Data_Binding_using_File.Views
{
    /// <summary>
    /// Interaction logic for HomePage.xaml
    /// </summary>
    public partial class HomePage : Page
    {
        public HomePage()
        {
            InitializeComponent();

            this.Loaded += HomePage_Loaded;
        }

        private void HomePage_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                // Binding
                this.cmbCountryList.DisplayMemberPath = "CountryName";
                this.cmbCountryList.SelectedValuePath = "CountryCode";
                this.cmbCountryList.ItemsSource = HomeBusinessLogic.LoadCountryList();
                this.cmbCountryList.Text = "Choose Country";
            }
            catch (Exception ex)
            {
                Console.Write(ex);
            }
        }
    }
}

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.

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

<Window x:Class="Data_Binding_using_File.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:Data_Binding_using_File"
        mc:Ignorable="d"
        Title="WPF - Dropdown Menu/Combobox Menu Data Binding using Text File"
        d:DesignHeight="480" d:DesignWidth="640">
    <Grid>
        <Grid.Background>
            <ImageBrush ImageSource="Content/img/main_bg.jpg"/>
        </Grid.Background>
        <Frame x:Name="mainFrame" 
               NavigationUIVisibility="Hidden"/>
    </Grid>
</Window>

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

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

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
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;

namespace Data_Binding_using_File
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            this.Loaded += MainWindow_Loaded;
        }

        private void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            this.mainFrame.Navigate(new Uri("/Views/HomePage.xaml", UriKind.Relative));
        }
    }
}

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

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



Conclusion

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


Disclaimer

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

No comments