2016-06-27 43 views
1

我有一个名为Person的类,它只有名称,年龄和性别属性。我也有一个List<Person> 5人(现在硬编码,但不相关)。我想通过XAML将其绑定到一个列表框,因此具有各性能三个的TextBlocks:将列表绑定到WPF中的列表框中

<ListBox.ItemTemplate> 
    <DataTemplate> 
     <StackPanel> 
      <TextBlock Text="{Binding Path=name}" /> 
      <TextBlock Text="{Binding Path=gender}" /> 
      <TextBlock Text="{Binding Path=age}" /> 
     </StackPanel> 
    </DataTemplate> 
</ListBox.ItemTemplate> 

的问题是,我不知道作为一个数据上下文或项目源或什么用什么。 任何想法?

+0

ListBox的的ItemsSource应你的硬编码列表。 – lokusking

回答

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

,并在后面的代码(视图模型):

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

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

+0

只为了完整性,“人”必须是一个特性。所以你必须写'public ObservableCollection People {get; set;}'。 – MyNewName

+0

糟糕,我的坏。我编辑了我的答案。谢谢 –