在WPF中将列表绑定到ListBox

5
我有一个名为Person的类,只有姓名、年龄和性别属性。我也有一个包含5个人的List<Person>(现在是硬编码的,但不相关)。我希望通过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>

问题在于我不知道该用什么作为数据上下文或项源,还有其他的选择。有什么想法吗?


ListBox的itemssource应该是你硬编码的List。 - lokusking
1个回答

11
<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>

在您的代码后台(ViewModel)中:

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

您可以省略绑定中的Path=,因为它是默认属性。


为了完整性,People 必须是一个属性。因此,您需要编写 public ObservableCollection<Person> People {get;set;} - MyNewName

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接