#967 – ListBox Data Binding Basics, part IV

In the earlier posts, we created an Actor class and then populated a list with a series of Actor objects.  We can now bind a ListBox to this list using its ItemsSource property.

    <StackPanel>
        <ListBox Margin="15" Width="250" Height="250"
                 ItemsSource="{Binding ActorList}"
                 DisplayMemberPath="NameAndDates"
                 SelectedItem="{Binding SelectedActor}"/>
        <Label Margin="10,0" Content="{Binding SelectedActor.KnownFor}"/>
    </StackPanel>

The ItemsSource property indicates that we want the ListBox filled with elements from our ActorList property, which is a collection of Actor objects.

The DisplayMemberPath property indicates that each entry in the list should be rendered as a string using the Actor.NameAndDates property.

The SelectedItem property indicates that when a user selects an item, our SelectedActor property should be set to refer to the selected Actor instance.  We demonstrate that by binding a Label element to a property of that selected actor.

967-001

Advertisement

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

One Response to #967 – ListBox Data Binding Basics, part IV

  1. Pingback: #970 – Avoid Working Directly with Items Collection | 2,000 Things You Should Know About WPF

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: