Search code examples
wpflisttemplateslistboxdatatemplate

What is wrong with the following code, list box items don't get displayed?


I want to display a listbox containng list items, I have the following template but it doesn't work, I also changed List l to ObservableList but still same result.

<Window.Resources>
    <DataTemplate x:Key="dataTemplate">
        <ListBox ItemsSource="{Binding Items}">
            <ListBox.ItemsPanel>
                <ItemsPanelTemplate>
                    <StackPanel Orientation="Horizontal"/>
                </ItemsPanelTemplate>
            </ListBox.ItemsPanel>
        </ListBox>
    </DataTemplate>
</Window.Resources>
<Grid>
    <ListBox x:Name="list1"/>

List<String> l = new List<String>();
    public MainWindow()
    {
        InitializeComponent();
        list1.ItemTemplate = (DataTemplate)FindResource("dataTemplate");
        l.Add("Hi");
        l.Add("there");

        list1.Items.Add(l);
    }

Solution

  • List<string> does not have a property called Items, so your binding is invalid

    To make it work, remove the path Items in the the binding so it binds directly to the list

    <DataTemplate x:Key="dataTemplate">
        <ListBox ItemsSource="{Binding }">
            <ListBox.ItemsPanel>
                <ItemsPanelTemplate>
                    <StackPanel Orientation="Horizontal"/>
                </ItemsPanelTemplate>
            </ListBox.ItemsPanel>
        </ListBox>
    </DataTemplate>