【问题标题】:Binding List to a ListBox in WPF将列表绑定到 WPF 中的列表框
【发布时间】:2016-06-27 07:11:28
【问题描述】:

我有一个名为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>

问题是我不知道将什么用作数据上下文或项目源或其他什么。 有什么想法吗?

【问题讨论】:

  • ListBox 的 itemssource 应该是你的硬编码列表。

标签: wpf data-binding itemssource


【解决方案1】:
<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&lt;Person&gt; People {get;set;}
猜你喜欢
  • 2011-08-28
  • 1970-01-01
  • 2011-05-07
  • 1970-01-01
  • 2011-01-30
  • 1970-01-01
  • 1970-01-01
  • 2018-10-23
  • 2014-11-05
相关资源
最近更新 更多