Aleksa Kojadinovic
Aleksa Kojadinovic

Reputation: 337

Binding List to a ListBox in WPF

I have a class called Person, with just name, age and gender properties. And I also have a List<Person> of 5 people (hard-coded for now, but not relevant). I want to bind it to a ListBox through XAML so it has three TextBlocks for each of the properties:

<ListBox.ItemTemplate>
    <DataTemplate>
        <StackPanel>
            <TextBlock Text="{Binding Path=name}" />
            <TextBlock Text="{Binding Path=gender}" />
            <TextBlock Text="{Binding Path=age}" />
        </StackPanel>
    </DataTemplate>
</ListBox.ItemTemplate>

The problem is that I don't know what to use as a data context or item source or whatever. Any ideas?

Upvotes: 5

Views: 8632

Answers (1)

Can Nguyen
Can Nguyen

Reputation: 1470

<ListBox ItemsSource="{Binding People}">
    <ListBox.ItemTemplate>
         <DataTemplate>
             <StackPanel>
                 <TextBlock Text="{Binding Path=name}" />
                 <TextBlock Text="{Binding Path=gender}" />
                 <TextBlock Text="{Binding Path=age}" />
             </StackPanel>
         </DataTemplate>
    </ListBox.ItemTemplate>

and in your code behind (ViewModel):

public ObservableCollection<Person> people = new ObservableCollection<Person>();
public ObservableCollection<Person> People { get { return people; } }

You can omit Path= in your bindings because it is the default property

Upvotes: 11

Related Questions