wemblem
wemblem

Reputation: 139

Populating a ListBox (WPF) with an ObservableCollection

I've perused all the related questions on this site, but for some reason I'm not able to populate my two ListBoxes with two ObservableCollections. Is the issue with my binding or somewhere in the model?

Model:

public class DataModel : INotifyPropertyChanged
{
    public ObservableCollection<object> List1
    {
        get
        {
            return this.List1;
        }
        set
        {
            this.List1 = value;
            this.OnPropertyChanged("List1");
        }
    }

    public ObservableCollection<object> List2
    {
        get
        {
            return this.List2;
        }
        set
        {
            this.List2 = value;
            this.OnPropertyChanged("List2");
        }
    }

    public DataModel(ObservableCollection<object> _list1, ObservableCollection<object> _list2)
    {
        this.List1 = _list1;
        this.List2 = _list2;
    }

    public event PropertyChangedEventHandler PropertyChanged;

    [NotifyPropertyChangedInvocator]
    protected virtual void OnPropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

XAML.cs:

public partial class UserControl1 : UserControl
{
    public ObservableCollection<object> l;
    public ObservableCollection<object> m;

    public UserControl1()
    {
        l = new ObservableCollection<object> { "test1a", "test1b" };
        m = new ObservableCollection<object> { "test2a", "test2b" };
        InitializeComponent();
        DataModel inst = new DataModel(l, m);
        this.DataContext = inst;
        this.TelProps.ItemsSource = l;
        this.SurProps.ItemsSource = m;
    }
}

XAML:

<Grid Name="Grid" DataContext="inst">
    <ListBox Name="FirstProps" 
             DataContext="{Binding Source=inst}"
             ItemsSource="{Binding List1}"
             DisplayMemberPath="List1" />
    <ListBox Name="SecondProps" 
             DataContext="{Binding Source=inst}"
             ItemsSource="{Binding List2}"
             DisplayMemberPath="List2" />
</Grid>

Upvotes: 1

Views: 655

Answers (1)

Reed Copsey
Reed Copsey

Reputation: 564403

You need to remove the DisplayMemberPath specifier. This is saying to look for the List1 property on each item of List1. Since List1 merely contains a set of strings, there is no List1 property on System.String, so you get a binding error.

Upvotes: 3

Related Questions