C# – Display custom object data to ListBox WPF


I have a ListBox in WPF application as :

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


I have three buttons: Add, Remove and Update that will add, remove and update items to the list box. I am adding Items to the ListBox my custom class object names objEmployee.
This custom class contains few properties: Id, Name, Address.

But, when I add the object to ListBox, then it will display items as

<Namespace Name>.<Custom Object name>

How can I bind any of the object property to this ListBox at Design or run time to acheive my functionality?

Best Solution

Couple of options:

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

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

If you want more control over the data that's displayed for each item (including custom layout etc) then you'll want to define a DataTemplate for each item in your ListBox. The easiest way to do this is by simply setting the ListBox's ItemTemplate property:

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

Have a read through the links I've provided and check out some of the example code on MSDN.

Related Question