C# – What do I have to change in the WPF databinding to get Listbox to show items

cdata-bindinglistboxwpf

I found this XAML in an example:

<Window x:Class="TestDataTemplate123.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:TestDataTemplate123"
    Title="Window1" Height="300" Width="300">
    <Window.Resources>
        <local:Customer x:Key="customers"/>
    </Window.Resources>
    <StackPanel>
        <TextBlock Text="Customers:"/>
        <ListBox ItemsSource="{Binding Source={StaticResource customers}}"/>
    </StackPanel>
</Window>

I'm trying to create the code behind but the following doesn't this work (it displays an empty set (I'm expecting a list of words that say TestDataTemplate123.Customer).

Window1.cs

using System.Collections.ObjectModel;
using System.Windows;

namespace TestDataTemplate123
{
    public partial class Window1 : Window
    {
        public static ObservableCollection<Customer> Customers()
        {
            return Customer.GetAllCustomers();
        }

        public Window1()
        {
            InitializeComponent();
        }
    }
}

Customer.cs:

using System.Collections.ObjectModel;

namespace TestDataTemplate123
{
    public class Customer
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public int Age { get; set; }

        public static ObservableCollection<Customer> GetAllCustomers()
        {
            ObservableCollection<Customer> customers = new ObservableCollection<Customer>();
            customers.Add(new Customer() {FirstName = "Jim", LastName = "Smith", Age = 23});
            customers.Add(new Customer() {FirstName = "John", LastName = "Jones", Age = 22});
            customers.Add(new Customer() {FirstName = "Jay", LastName = "Anders", Age = 21});
            return customers;
        }
    }
}

I've tried many different combinations of xmlns:local, x:Key, StaticResource, DataContext but I get various errors or an empty ListBox.

What do I have to change so that I it just lists out TestDataTemplate123.Customer so I can go on making my DataTemplate?

Best Answer

Your XAML has you binding the items in your list to a single instance of Customer. You need to bind to a list of customers.

Since you're doing most of the work in the code-behind, I'd ditch the <local:Customer /> declaration in the XAML, as well as the ItemsSource attribute, and set it in your code:

public Window1()
{
    InitializeComponent();
    listBox1.ItemsSource = Customer.GetAllCustomers();
}

Note that I've given the ListBox a name so I can refer to it from the code behind. Do that like this:

<ListBox x:Name="listBox1" />
Related Topic