Display custom object data in ListBox WPF

I have a ListBox in a WPF application like:

<ListBox HorizontalAlignment="Left" Margin="16,37,0,16" Name="lbEmpList" Width="194" SelectionChanged="lbEmpList_SelectionChanged" FontSize="12" SelectionMode="Single"> </ListBox> 

I have three buttons: Add, Delete and Update, which will add, delete and update items in the list. I am adding Items to the ListBox with my objEmployee class object names. This custom class contains several properties: Id, Name, Address.
But when I add an object to the ListBox, it will display the elements as

 <Namespace Name>.<Custom Object name> 

How to associate any property of an object with this list in Design or runtime to fulfill my functions?

+6
c # wpf
source share
1 answer

A couple of options:

The first, easiest option is to set the ListBox DisplayMemberPath property to the property of your custom object. Therefore, if your Employee class has a LastName property, you can do this:

 <ListBox DisplayMemberPath="LastName" ... /> 

If you need more control over the data displayed for each item (including custom layout, etc.), you must define a DataTemplate for each item in your ListBox. The easiest way to do this is to simply set the ListBox ItemTemplate property:

 <ListBox ...> <ListBox.ItemTemplate> <DataTemplate> <StackPanel> <TextBlock Text="{Binding FirstName}" /> <TextBlock Text="{Binding LastName}" /> </StackPanel> </DataTemplate> </ListBox.ItemTemplate> </ListBox> 

Read the links I provided and check out some code examples on MSDN.

+24
source share

All Articles