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

时间:2011-02-08 14:01:54

标签: c# silverlight

我简化了这一点只是为了展示展示问题所需要的东西 - 即虽然8个项目明显在列表框中,但它们没有内容,即“名称”不显示,它们只是空白。如果我在设置ItemSource之后设置断点,我可以看到源已经正确填充了集合,所以我假设我的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>

1 个答案:

答案 0 :(得分:5)

尽管它不是一个真正的问题(参见前面的评论),但是你的问题源于你的ToolBoxItem上的Field'Name'需要是一个能够绑定的Property。所以改成它:

public string Name {get; set;}

它应该有用。

相关问题