XAML
<UserControl x:Class="MultiColumnListBox.Page"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Width="400" Height="300">
<Grid x:Name="LayoutRoot" Background="White">
<ListBox x:Name="CustomerList" >
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Width="50" Text="{Binding ID}"/>
<TextBlock Width="50" Text="{Binding FName}" />
<TextBlock Width="50" Text="{Binding LName}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</UserControl>
C#
public partial class Page : UserControl
{
public Page()
{
InitializeComponent();
List<Customers> cust = new List<Customers>();
cust.Add(new Customers(1, "Harry", "Smith"));
cust.Add(new Customers(2, "Tim", "Goldberg"));
cust.Add(new Customers(3, "Jenny", "McKallan"));
CustomerList.ItemsSource = cust;
}
}
public class Customers
{
public Customers(int id, string fnm, string lnm)
{
ID = id;
FName = fnm;
LName = lnm;
}
public int ID { get; set; }
public string FName { get; set; }
public string LName { get; set; }
}
VB.NET
Partial Public Class Page
Inherits UserControl
Public Sub New()
InitializeComponent()
Dim cust As List(Of Customers) = _
New List(Of Customers)()
cust.Add(New Customers(1, "Harry", "Smith"))
cust.Add(New Customers(2, "Tim", "Goldberg"))
cust.Add(New Customers(3, "Jenny", "McKallan"))
CustomerList.ItemsSource = cust
End Sub
End Class
Public Class Customers
Public Sub New(ByVal id As Integer, _
ByVal fnm As String, ByVal lnm As String)
id = id
FName = fnm
LName = lnm
End Sub
Private privateID As Integer
Public Property ID() As Integer
Get
Return privateID
End Get
Set(ByVal value As Integer)
privateID = value
End Set
End Property
Private privateFName As String
Public Property FName() As String
Get
Return privateFName
End Get
Set(ByVal value As String)
privateFName = value
End Set
End Property
Private privateLName As String
Public Property LName() As String
Get
Return privateLName
End Get
Set(ByVal value As String)
privateLName = value
End Set
End Property
End Class
All we have done here is change the template of the ListBox and defined our own. We then bind the List
Thanks!
ReplyDeleteUsed the example in a WPF project. The ItemsSource property was not exposed by default in WPF. Added a property to the user control, setting it to the ItemsSource of the ListBox inside the user control.
Glad the sample helped you!
ReplyDeletegreat post. simple, but good!
ReplyDeleteYou sir, are a genius. I've been searching an hours for something as simple as this in wpf but with no luck.
ReplyDeleteThanks, and have my respect.