ARTICLE

WPF Data Binding

Posted by Raj Kumar Articles | WPF September 05, 2011
This article demonstrates the concept of data binding in WPF.
Reader Level:
Download Files:
 

Getting Started

Creating a new WPF Application:

  • Open Visual Studio 2010.

  • Go to File => New => Project

  • Select Windows from the Installed templates and choose WPF application

  • Enter the Name and choose the location.

Click OK.

First of all add a new class

using System.ComponentModel;
using System.Collections.ObjectModel; 

public class User : INotifyPropertyChanged
    {
       
      public event PropertyChangedEventHandler PropertyChanged;   
        protected void NotifyPropertyChanged(string propertyName)
           {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
 
        string firstName;
        public string FirstName
        {
            get{return firstName;}
            set {firstName = value;
            NotifyPropertyChanged("FirstName");
            }
        }
 
        string lastName;
        public string LastName
        {
            get { return lastName; }
            set { lastName = value;
                NotifyPropertyChanged("LastName"); }
        }
 
        string country;
        public string Country
        {
            get { return country; }
            set { country = value;
            NotifyPropertyChanged("Country");
            }
        }
 
        public User(string firstName, string lastName, string country)
        {
            this.firstName = firstName;
            this.lastName = lastName;
            this.country = country;
        }

        public User() : this("Raj","Kumar","India")
        {
            // TODO: Complete member initialization
        }
    }

public class UserNames : ObservableCollection<User> { }

MainPage.xaml

<Grid>
        <DockPanel x:Name="userNameDocpanel" >
            <TextBlock DockPanel.Dock="Top">
                <TextBlock VerticalAlignment="Center">First Name</TextBlock>
                <TextBlock Text="{Binding Path=FirstName}"></TextBlock>
                <TextBlock VerticalAlignment="Center">Last Name</TextBlock>
                <TextBlock Text="{Binding Path=LastName}"></TextBlock>
                <TextBlock VerticalAlignment="Center">Country</TextBlock>
                <TextBlock Text="{Binding Path=Country}"></TextBlock>
            </TextBlock>
            <Button DockPanel.Dock="Bottom" x:Name="AddUser" Height="20" Width="100" Click="AddUser_Click">Add User</Button>
            <ListBox ItemsSource="{Binding}" IsSynchronizedWithCurrentItem="True" Height="271">
                <ListBox.ItemTemplate>
                    <DataTemplate>
                        <TextBlock>
                            <TextBlock Text="{Binding Path=FirstName}"></TextBlock>
                            <TextBlock Text="{Binding Path=LastName}"></TextBlock>
                            <TextBlock Text="{Binding Path=Country}"></TextBlock>
                        </TextBlock>
                    </DataTemplate>
                </ListBox.ItemTemplate>
            </ListBox>
        </DockPanel>
    </Grid>

MainPage.xaml.cs 

UserNames userNames;
        public MainWindow()
        {
            InitializeComponent();
            this.userNames = new UserNames();
            userNameDocpanel.DataContext = userNames;
        }
 
        private void AddUser_Click(object sender, RoutedEventArgs e)
        {
          this.userNames.Add(new User());
        }

 Now run the application.  

 img1.jpg

Image 1. 

When you click on Add User button. 

 img2.jpg

Image 2.

Now let's start how to bind using resource 

First thing you have to comment the code behind binding code and this resource code on .xaml page and this app namespace 

xmlns:local="clr-namespace:WpfDataBinding" 
<Window.Resources>
        <local:UserNames x:Key="names">
            <local:User FirstName="Raj" LastName="Kumar" Country="India"></local:User>
            <local:User FirstName="Joe" LastName="Telmadge" Country="USA"></local:User>
            <local:User FirstName="Deny" LastName="Sonak" Country="Australia"></local:User>
            <local:User FirstName="Stephen" LastName="Hoffman" Country="USA"></local:User>
            <local:User FirstName="Riya" LastName="Malhotra" Country="Canada"></local:User>
            <local:User FirstName="Kapil" LastName="Kapoor" Country="London"></local:User>
        </local:UserNames>
    </Window.Resources>
 

Now change the DataContext name 

<DockPanel x:Name="userNameDocpanel" DataContext="{StaticResource names}" >
            <TextBlock DockPanel.Dock="Top">
                <TextBlock VerticalAlignment="Center">First Name</TextBlock>
                <TextBlock Text="{Binding Path=FirstName}"></TextBlock>
                <TextBlock VerticalAlignment="Center">Last Name</TextBlock>
                <TextBlock Text="{Binding Path=LastName}"></TextBlock>
                <TextBlock VerticalAlignment="Center">Country</TextBlock>
                <TextBlock Text="{Binding Path=Country}"></TextBlock>
            </TextBlock>
            <Button DockPanel.Dock="Bottom" x:Name="AddUser" Height="20" Width="100" Click="AddUser_Click">Add User</Button>
            <ListBox ItemsSource="{Binding}" IsSynchronizedWithCurrentItem="True" Height="271">
                <ListBox.ItemTemplate>
                    <DataTemplate>
                        <TextBlock>
                            <TextBlock Text="{Binding Path=FirstName}"></TextBlock>
                            <TextBlock Text="{Binding Path=LastName}"></TextBlock>
                            <TextBlock Text="{Binding Path=Country}"></TextBlock>
                        </TextBlock>
                    </DataTemplate>
                </ListBox.ItemTemplate>
            </ListBox>
        </DockPanel>
 

Run the application to see this result. 

 img3.jpg

Image 3.

img4.jpg 

Image 4.

This is it. For more information I have attached sample application. Question and comments are most welcome, drop me a line in c-sharpcorner comments section. 

Login to add your contents and source code to this article
post comment
     

This works listBox1.ItemsSource = temp; if you are not binding listbox on .xaml page. if you are binding on .xaml page then you have to set listbox data context listBox1.DataContext = temp;

Posted by Raj Kumar Sep 09, 2011

This example demonstrates OneWay binding as shown clicking the Add button will not change the bound list from the XAML, this is good if you dont want users to modify the information. To change the list would require changing the DataContext of the listbox to something new, for example: private void AddUser_Click(object sender, RoutedEventArgs e) { // the list was prepopulated from the Xaml // for additions we will copy the list and add the new data List<User> temp = new List<User>(); foreach (User u in listBox1.Items ) { temp.Add(u); } temp.Add(new User()); // listBox1.DataContext = temp; // this works listBox1.ItemsSource = temp; // or this works

Posted by p quincoses Sep 07, 2011
COMMENT USING
PREMIUM SPONSORS
Over-C is a holistic consortium of communications and technology specialists. We build, deploy and market both business as well as consumer products and solutions.
Join a Chapter
SPONSORED BY
  • PDF reports have never been easier to create. With our included WYSIWYG Designer, you can layout your reports, set up your data source and let DynamicPDF ReportWriter do the rest.
Get Career Advice from Experts