views:

431

answers:

3

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}" />
+3  A: 

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" />
Ray
A: 

Ray, Thanks but this didn't do anything. Still, my listbox is empty.

As I showed in the posted code, the Data property is explicitly set to the datacontext in the UserControl_Loaded event.

Gustavo Cavalcanti
It should work, I did a simple test. I'll add my sample code to my post above.
Ray
A: 

You're right Ray. It works. Thanks you so much!

Gustavo Cavalcanti