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?
<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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With