Ale*_*vic 3 data-binding wpf itemssource
我有一个叫做Person
名字,年龄和性别属性的课程.我也有List<Person>
5个人(现在硬编码,但不相关).我想通过XAML将它绑定到ListBox,因此它为每个属性都有三个TextBlock:
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding Path=name}" />
<TextBlock Text="{Binding Path=gender}" />
<TextBlock Text="{Binding Path=age}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
Run Code Online (Sandbox Code Playgroud)
问题是我不知道用什么作为数据上下文或项目源或其他什么.有任何想法吗?
<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>
Run Code Online (Sandbox Code Playgroud)
并在您的代码后面(ViewModel):
public ObservableCollection<Person> people = new ObservableCollection<Person>();
public ObservableCollection<Person> People { get { return people; } }
Run Code Online (Sandbox Code Playgroud)
您可以Path=
在绑定中省略它,因为它是默认属性