开发者

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

开发者 https://www.devze.com 2023-02-09 10:58 出处:网络
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, i.e. \'Name\' does not display, they are jus

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, i.e. 'Name' does not display, they are just blanks. 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. Here is the code and xaml:

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

    public MainPage()
    {
        InitializeComponent();

        InitToolboxItems();
        lstToolbox.ItemsSource = ToolboxItems;
    }

    private void InitToolboxItems()
    {
        ToolboxItems = new ObservableCollection<ToolboxItem&g开发者_开发问答t;();

        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. So change it to:

public string Name {get; set;}

and it should work.

0

精彩评论

暂无评论...
验证码 换一张
取 消