Scope
This article intends to introduce the concept of Data Binding in WPF, presenting, as an example, a DataGrid that is populated using a custom List(Of). Data will be edited using controls suach as TextBox and DatePicker that will take their data source from the grid itself.
Introduction
It is widely known that one of the major features introduced with Windows Presentation Foundation resides in the ability to easily connect the user controls (and objects) with data sources of various complexities, leaving the task of their representation to the framework (on which you can always apply later customizations, nonetheless). As an example of a possible usage scenario, we assume here to have a grid expose data from a given customized structure and later to make possible its variation using simple text controls.
An example class
Let's suppose we have a hypothetical class Articolo, that will allow us to define products to store, in their terms of product's code (Codice), a description (Descrizione), and expiration date (DataScadenza). We'll declare that the class is reductive, but useful for our means, as follows.
- Public Class Articolo
- Dim _codice As String
- Dim _descrizione As String
- Dim _datascadenza As Date
- Public ReadOnly Property Codice As String
- Get
- Return _codice
- End Get
- End Property
- Public Property Descrizione As String
- Get
- Return _descrizione
- End Get
- Set(value As String)
- _descrizione = value
- End Set
- End Property
- Public Property DataScadenza As Date
- Get
- Return _datascadenza
- End Get
- Set(value As Date)
- _datascadenza = value
- End Set
- End Property
- Public Sub New(codart As String, desart As String)
- _codice = codart
- _descrizione = desart
- _datascadenza = New Date(Now.Year + 1, Now.Month, Now.Day)
- End Sub
- End Class
In the class constructor only the parameters for code and description are requested. The expiration date is set a year in the future. Properties that define the class are editable, with the only exception of Codice (product code), that cannot be altered after its creation.
Next, we'll populate a list of products with some example data, useful for the next steps. Let's suppose we have a WPF window named MainWindow.xaml. We'll create an event manager for the Loaded event, such as the XAML resembling the following.
- <Window
- xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
- xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
- xmlns:local="clr-namespace:ERP_test" x:Class="MainWindow"
- Title="MainWindow" Height="269" Width="563" Loaded="Window_Loaded">
- </Window>
The code behind the event will be:
- Dim prodotti As List(Of Articolo)
- Private Sub Window_Loaded(sender As Object, e As RoutedEventArgs)
- prodotti = New List(Of Articolo)
- prodotti.Add(New Articolo("Prodotto01", "ARTICOLO TEST"))
- prodotti.Add(New Articolo("Prodotto02", "PROVA"))
- prodotti.Add(New Articolo("Prodotto03", "NESSUNA DESCRIZIONE"))
- End Sub
Data Binding on DataGrid
In our window we'll add a DataGrid control, named DataGrid1. Having our structure defined code-side, we must work on this side to link the control to its data source. The binding will be obtained using the control's ItemsSource property. Our Loaded event will be modified as follows.
- Dim prodotti As List(Of Articolo)
- Private Sub Window_Loaded(sender As Object, e As RoutedEventArgs)
- prodotti = New List(Of Articolo)
- prodotti.Add(New Articolo("Prodotto01", "ARTICOLO TEST"))
- prodotti.Add(New Articolo("Prodotto02", "PROVA"))
- prodotti.Add(New Articolo("Prodotto03", "NESSUNA DESCRIZIONE"))
- DataGrid1.ItemsSource = prodotti
- End Sub

Data Binding between controls: Datagrid on TextBox and DatePicker
As previously described, we are not interested in having a mere list of products. We want to be able to view the product's details scrolling that list. In realizing this kind of implementation, we'll use some TextBoxes, executing a binding between them (as recipients) and the DataGrid (the source), allowing recipient controls (TextBox, or DatePicker in case of expiration date) to modify their source in turn. Let's modify our window as follows.
The properties that expose the control's value in the TextBox and DatePicker are, respectively, Text and SelectedDate. It is therefore necessary to set the data binding on these properties. Essentially, after individuating the property that will receive a specific data, we must indicate its source, and other information (some of which are optional) that will determine how the data are exchanged. In our case, desiring to modify the content of DataGrid using the variation of recipient controls, we must use some kind of bidirectional approach.
As operations to be executed between controls, it is possible to intervene directly on XAML code, indicating how TextBoxes and the DatePicker must be linked to the DataGrid. The code pertinent to the three controls will be modified as follows.
- <TextBox HorizontalAlignment="Left" Height="23" Margin="445,42,0,0"
- TextWrapping="Wrap" VerticalAlignment="Top" Width="181"
- Text="{Binding SelectedItem.Codice,ElementName=DataGrid1 , Mode=OneWay }"/>
- <TextBox HorizontalAlignment="Left" Height="23" Margin="445,70,0,0"
- TextWrapping="Wrap" VerticalAlignment="Top" Width="181"
- Text="{Binding SelectedItem.Descrizione,ElementName=DataGrid1 , Mode=TwoWay }"/>
- <DatePicker HorizontalAlignment="Left" Margin="445,98,0,0"
- VerticalAlignment="Top" Width="181"
- SelectedDate="{Binding SelectedItem.DataScadenza,ElementName=DataGrid1 ,Mode=TwoWay }"/>
In this case, we'll see the source control is set on DataGrid1, from which we read the Codice property (belonging to the Articolo class) of the currently SelectedItem. The Binding's mode is mono-directional, that is from the source (DataGrid1) to the destination (TextBox), and not vice versa. In fact, we defined the Codice property as read-only (see snippet 1) and any attempt to change its value will raise an exception.
Similarly, in the two remaining cases we'll have always DataGrid1 as source control, referenced properties will be Descrizione (description) and DataScadenza (expiration date), but the binding’s mode will be TwoWay, or bidirectional: modifying the control’s content will result in updating its source property/control, or DataGrid1 (and, for extension, the list connected to it).
Running our program, and trying to position ourselves on the second record (for example) and modifying the data, we can verify the proper update of linked control’s data:
Afterwords: Alternative method for DataGrid population
We saw here a method for populating a DataGrid that involves a List(Of <Our_Class>). Speaking of WPF binding flexibility, there are other methods using which we could populate the contents of a control. For example, our class Articolo could be referred directly into the XAML of our grid. If we desire to provide our DataGrid some records to start with, we could do that as follows.
- <DataGrid Name="DG1" HorizontalAlignment="Left" Height="153" Margin="10,10,0,0" VerticalAlignment="Top" Width="305" xmlns:local="clr-namespace:WinTest" >
- <DataGrid.Columns >
- <DataGridTextColumn Header="Codice" Binding="{Binding Codice}"/>
- <DataGridTextColumn Header="Descrizione" Binding="{Binding Descrizione}"/>
- <DataGridTextColumn Header="Data di scadenza" Binding="{Binding DataScadenza}"/>
- </DataGrid.Columns>
- <local:Articolo Codice="CODE_01" Descrizione="MSDN TEST" DataScadenza="2014-12-01" />
- </DataGrid>

From a situation like that, we could add other rows code-side, using the Item collection exposed by DataGrid. Assuming our DataGrid's name is DataGrid1, we could, for example, add a second row to it, using in the Loaded event something like that.
- DataGrid1.Items.Add( New Articolo("CODE_02", "MSDN TEST 2") )
Running now our program will result in the following window.
Please note: as far as there are dynamically or statically generated rows, in other words the Item collection is not empty, it's not possibile to use the ItemsSource property discussed above. In order to bind a structure to our DataGrid, we must first empty Item collection (for example, with something like: DataGrid1.Items.Clear()), and only then we'll be able to successfully set the ItemsSource property.
Conclusion
Obviously, we had discussed here a small example, compared to the potential offered by such technology: nonetheless, I hope it was useful for those approaching this method for the first time. Happy coding.

Santhakumar MunuswamyPosted May 5, 2015, 2:30 PM
Thanks for nice article
NitinPosted May 5, 2015, 1:40 PM
good one