Data binding with Item template for List box:Create a new window, then go to XAML source and write the following code:
[csharp]
<Window x:Class="WPFListbox.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="WPF | ListBox" Height="300" Width="300" Background="Black">
<Grid Margin="10">
<ListBox Name="lstempinfo" HorizontalContentAlignment="Stretch" Width="200"
Margin="0,10,0,10" Background="LightPink" FontFamily="Tahoma" FontWeight="Bold">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding EmpName}" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</Window>
[/csharp]
Then the window becomes like below:
Now go to code behind file and write the following code:
[csharp]using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace WPFListbox
{
/// <summary>
/// Interaction logic for ListBox1.xaml
/// </summary>
public partial class ListBox1 : Window
{
public ListBox1()
{
InitializeComponent();
lstempinfo.ItemsSource = lstemp;
GetEmp();
}
List&lt;EmployeeInfo&gt; lstemp = new List&lt;EmployeeInfo&gt;();
void GetEmp()
{
lstemp.Add(new EmployeeInfo() { Empid = 111, EmpName = "SPlessons" });
lstemp.Add(new EmployeeInfo() { Empid = 112, EmpName = "SPlessons" });
lstemp.Add(new EmployeeInfo() { Empid = 113, EmpName = "SPlessons" });
lstemp.Add(new EmployeeInfo() { Empid = 114, EmpName = "SPlessons" });
lstemp.Add(new EmployeeInfo() { Empid = 115, EmpName = "SPlessons" });
lstemp.Add(new EmployeeInfo() { Empid = 116, EmpName = "SPlessons" });
lstemp.Add(new EmployeeInfo() { Empid = 117, EmpName = "SPlessons" });
lstemp.Add(new EmployeeInfo() { Empid = 111, EmpName = "SPlessons" });
lstemp.Add(new EmployeeInfo() { Empid = 112, EmpName = "SPlessons" });
lstemp.Add(new EmployeeInfo() { Empid = 113, EmpName = "SPlessons" });
lstemp.Add(new EmployeeInfo() { Empid = 114, EmpName = "SPlessons" });
lstemp.Add(new EmployeeInfo() { Empid = 115, EmpName = "SPlessons" });
lstemp.Add(new EmployeeInfo() { Empid = 116, EmpName = "SPlessons" });
lstemp.Add(new EmployeeInfo() { Empid = 117, EmpName = "SPlessons" });
}
public class EmployeeInfo
{
public int Empid { get; set; }
public string EmpName { get; set; }
}
}
}[/csharp]
Now run the application, the result appears like below.