In this demonstration we learn how to implement complex data binding in silver light. Here we show that how to bind data with list box control. We know that complex data binding means to bind data with such type of controls which have a capacity to show more than one value at a time. Best example for complex data binding is ListBox control, ComboBox control and DataGrid control etc. Here firstly we see that how to bind data with ListBox control.
Write following XAML control to create a User Interface for this demonstration
<Grid x:Name="LayoutRoot" Background="White">
<ListBox x:Name="lstBox1" Width="100" VerticalAlignment="Top" Height="50" ItemsSource="{Binding}">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}"></TextBlock>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
Create a class name Employee
public class Employee
{
public string Name { get; set; }
public string Age { get; set; }
public string City { get; set; }
}
Create a method named GetEmployeeData() in MainPage class
public List<Employee> GetEmployeeData()
{
List<Employee> emp = new List<Employee>();
emp.Add(new Employee() { Name = "Awadhendra" });
emp.Add(new Employee() { Name = "Abhishek" });
emp.Add(new Employee() { Name = "Amit" });
emp.Add(new Employee() { Name = "Haider" });
emp.Add(new Employee() { Name = "Sachindra" });
emp.Add(new Employee() { Name = "Uttam" });
return emp;
}
At the load event of user control write down the following code
private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
lstBox1.DataContext = GetEmployeeData();
}
Save your application and then execute it to see the demonstration
John Smith
12-Mar-2011Anonymous User
12-Mar-2011