Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display custom object data to ListBox WPF

Tags:

c#

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">

</ListBox>

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?

like image 338
Sachin Gaur Avatar asked Feb 23 '09 04:02

Sachin Gaur


1 Answers

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 ...>
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel>
                <TextBlock Text="{Binding FirstName}" />
                <TextBlock Text="{Binding LastName}" />
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

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

like image 80
Matt Hamilton Avatar answered Sep 22 '22 03:09

Matt Hamilton