Question

I want to have a User Control that takes a collection of People (property "Data") and displays them in a list box. When I run my app nothing shows in the listbox. Can you please point out what I'm doing wrong? Thanks!!!

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
    public override string ToString()
    {
        return Name + "(" + Age + ")";
    }
}

User Control: (uc1.xaml.cs)

public partial class uc1
{
    public static readonly DependencyProperty DataProperty = DependencyProperty.Register("Data", typeof (List<Person>), typeof (uc1));

    public List<Person> Data
    {
        get { return (List<Person>) GetValue(DataProperty); }
        set { SetValue(DataProperty, value); }
    }

    public uc1()
    {
        InitializeComponent();
    }

    private void UserControl_Loaded(object sender, RoutedEventArgs e)
    {
        DataContext = Data;
    }
}

(uc1.xaml)

<ListBox ItemsSource="{Binding Name}" />
Was it helpful?

Solution

The ItemsSource property controls the list of items that are displayed in the listbox. If you want the ListBox to display one line for each person, you need to set the ItemsSource to bind directly to the DataContext. Then you use the DisplayMemberPath property to control which property of the Person class to show.

Here's my sample code that works for me. The person class is the same.

The Window1.xaml.cs:

public partial class Window1 : Window
{
    public Window1()
    {
        InitializeComponent();
        List<Person> Data = new List<Person>();
        Data.Add(new Person { Name = "Test 1", Age = 5 });
        Data.Add(new Person { Name = "Test 2", Age = 10 });
        this.DataContext = Data;
    }
}

The Window1.xaml

<ListBox ItemsSource="{Binding}" DisplayMemberPath="Name" />
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top