【发布时间】:2015-03-15 05:37:18
【问题描述】:
我正在尝试将 ObservableCollection 绑定到 ItemsControl。我创建了一个具有一些属性的名为 Persons 的类。然后我创建了一个 ObservableCollection 并在其中添加了一些 Persons。
如果我给 ItemsControl 一个 x:Name="PersonHolder" 并将 ItemsSource 添加到 PersonHolder.ItemsSource = people 那么一切正常。但是,如果我尝试在 XAML 中添加具有绑定的人员...没有结果。
这是 XAML:
<StackPanel Background="White">
<ItemsControl ItemsSource="{Binding persons}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</StackPanel>
来自 C# 的一些代码
public ObservableCollection<Person> persons { get; set; }
public MainWindow()
{
InitializeComponent();
persons = new ObservableCollection<Person>();
persons.Add(new Person { Name = "Peter" });
}
public class Person
{
public string Name { get; set; }
}
希望你能帮助我。
最好的问候。
【问题讨论】:
-
Control的DataContext在哪里设置?
标签: c# wpf xaml binding observablecollection