Monday 23 January 2012

Data Binding In WPF


Data Binding In WPF

Objective

Here in this tutorial we are going to bind data from a collection (LIST) to XAML. We are going to display
Image, Name, Age and Email id of a Person.


Step 1
Open Visual Studio 2008; create a New Project as WPF application. Give this name as Display.
 
Step 2

Add a business logic class. Right click in solution explorer then add a new class called Person

namespace Display{public partial class Window1 : Window{
public Window1(){
InitializeComponent();
List<Person> persons = new
List<Person>()
{
new Person{Name=“Anuska Sharama”,Age=21,Email=“anuska@xyz.com”,Image=“anuska.jpg”},
new Person {Name=“Asin”,Age=26,Email=“asin@xyz.com”,Image=“asin.jpg”},
new Person{Name=“Deepika”,Age=25,Email=“deepika@xyz.com”,Image=“deepika.jpg”}
} } }}

 Step 3
 
Now it is time to write XAML code and bind collection persons to List of XAML.Create a Listbox in XAML as follows

<ListBox x:Name=”list1″>
</ListBox>

Name it as list1. Then bind this list1 to collection persons. So again go to

Windows.xaml.cs

file and add this line of code after creating collection persons
list1.ItemsSource = persons;
list1.ItemsSource = persons;



Step 4


Now add a Item Template and Data template inside listbox in xaml file. Bind images to List box . Now again add Stack panel with orientation Vertical. Then add three labels to display Name, age and email.

Complete Xaml code will look like

<Window x:Class=”Display.Window1″
xmlns=http://schemas.microsoft.com/winfx/2006/xaml/presentation

xmlns:x=http://schemas.microsoft.com/winfx/2006/xaml

Title=”Window1″ Height=”300″ Width=”300″>

<Grid>
 <ListBox x:Name=”list1″>
<ListBox.ItemTemplate>

<DataTemplate>

<StackPanel Orientation=”Horizontal”>

<Image Source=”{Binding Image}” Height=”100″ Stretch=”UniformToFill” />
<StackPanel Orientation=”Vertical”>
<Label FontFamily=”Tahoma” FontSize=”20″ Content=”{Binding Name}” />
<Label FontFamily=”Tahoma” FontSize=”20″ Content=”{Binding Age}” />
<Label FontFamily=”Tahoma” FontSize=”20″ Content=”{Binding Email}” />
</StackPanel>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</Window>
Run the code to get the desired output.
 
Happy Coding
 
Posted by

No comments :