Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 414
Aleksa Kojadinovic Avatar asked Jun 27 '16 07:06

Aleksa Kojadinovic


1 Answers

<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

like image 166
Can Nguyen Avatar answered Sep 30 '22 10:09

Can Nguyen