在我的列表框中看不到项目

Can't see the items on my ListBox

我试图定义 ListBox 以显示我在某些集合中定义的所有元素。

代码:

public class Element
{
    private string _name;
    public string Name { get { return _name; } }

    public Element(string name)
    {
        _name = name;
    }
}

public class ElementCollection
{
    public List<Element> Elements
    {
        get;
        set;  
    }
}





  <ListBox ItemsSource="{Binding ElementCollection}">
        <ListBox.ItemTemplate>
             <DataTemplate>
                 <StackPanel Orientation="Vertical">
                    <TextBlock Text="{Binding Element.Name}"/>
                 </StackPanel>
             </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>

我做了 'DataContext',所有数据都在正确的位置。

我做错了什么?

你是 binding 到保存集合的 class,而不是实际集合 - 尝试将你的 ItemSource 改为 {Binding ElementCollection.Elements}。此外,您的 Textbox 已绑定到 Element.Name,您不需要它,因为它会在您的项目中查找 Name 属性:

<ListBox ItemsSource="{Binding ElementCollection.Elements}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Vertical">
                <TextBlock Text="{Binding Name}"/>
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>