Reader Level:
ARTICLE

WPF Data Binding

Posted by Raj Kumar Articles | WPF September 05, 2011
This article demonstrates the concept of data binding in WPF.
  • 0
  • 0
  • 9405
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. 

COMMENT USING