SIGN UP MEMBER LOGIN:    
ARTICLE

WPF Data Binding

Posted by Raj Kumar Articles | WPF with C# 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
share 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
Become a Sponsor
PREMIUM SPONSORS
  • Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
    ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications. Visit DynamicPDF here
Team Foundation Server Hosting
Become a Sponsor