简体   繁体   English

如何从可观察的集合中正确填充列表框?

[英]How do I correctly populate a listbox from an observable collection?

I've simplified this just to show what is needed to demonstrate the problem - which is that while 8 items are clearly in the listbox they have no content, ie 'Name' does not display, they are just blanks. 我简化了这一点只是为了展示展示问题所需要的东西 - 即虽然8个项目明显在列表框中,但它们没有内容,即“名称”不显示,它们只是空白。 If I set a breakpoint just after the ItemSource has been set I can see that the the source has been correctly populated with the collection so I assume something must be wrong with my xaml. 如果我在设置ItemSource之后设置断点,我可以看到源已经正确填充了集合,所以我假设我的xaml必定是错误的。 Here is the code and xaml: 这是代码和xaml:

public partial class MainPage : UserControl
{
    private ObservableCollection<ToolboxItem> ToolboxItems;

    public MainPage()
    {
        InitializeComponent();

        InitToolboxItems();
        lstToolbox.ItemsSource = ToolboxItems;
    }

    private void InitToolboxItems()
    {
        ToolboxItems = new ObservableCollection<ToolboxItem>();

        ToolboxItems.Add(new ToolboxItem(name: "Item1"));
        ToolboxItems.Add(new ToolboxItem(name: "Item2"));
        ToolboxItems.Add(new ToolboxItem(name: "Item3"));
        ToolboxItems.Add(new ToolboxItem(name: "Item4"));
        ToolboxItems.Add(new ToolboxItem(name: "Item5"));
        ToolboxItems.Add(new ToolboxItem(name: "Item6"));
        ToolboxItems.Add(new ToolboxItem(name: "Item7"));
        ToolboxItems.Add(new ToolboxItem(name: "Item8"));
    }

    public struct ToolboxItem
    {
        public String Name;
        public ToolboxItem(String name) { Name = name; }
    }
}

<Grid x:Name="LayoutRoot" Background="White">
    <ListBox Name="lstToolbox" Width="200" Height="280">
        <ListBox.ItemTemplate>
            <DataTemplate>
              <TextBlock Text="{Binding Name}" Width="100" Height="20" />
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
</Grid>

Even though it isn't really a Question (cf. earlier comments), your problem stems from the fact that the Field 'Name' on your ToolBoxItem needs to be a Property to be able to bind to. 即使它不是一个真正的问题(参见前面的评论),你的问题源于你的ToolBoxItem上的字段'名称'需要是一个能够绑定的属性。 So change it to: 所以改成它:

public string Name {get; set;}

and it should work. 它应该工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM