Eternal21
Eternal21

Reputation: 4664

Binding listview to a property in another class

I have the following static class

static class ContactSettings
{
    static ObservableCollection<Contact> _contactCollection = new ObservableCollection<Contact>();

    public static ObservableCollection<Contact> ContactCollection
    {
        get { return _contactCollection; }
    }
}

where Contact is a class with Contact.Name, and Contact.Address string properties.

I want to bind the ContactCollection above to a WPF ListView that resides in a Window.

Here's my ListView XAML definition

<ListView x:Name="_contactListView" DataContext="{Binding Path=ContactSettings}" ItemsSource="{Binding ContactSettings.ContactCollection}">
   <ListView.View>
      <GridView>
         <GridViewColumn Header="Name" DisplayMemberBinding="{Binding Name}" />
         <GridViewColumn Header="Address" DisplayMemberBinding="{Binding Address}" />                                        
      </GridView>
   </ListView.View>
</ListView>

The binding doesn't work. I am pretty sure the problem is with the DataContext and ItemSource properties inside XAML. I can get the code to work if I move the ContactCollection inside the Window class, and set DataContext to Self. The problem is I don't how to tell ListView to bind to a collection inside another class. Thanks for your help.

Upvotes: 3

Views: 2033

Answers (1)

Justin Pihony
Justin Pihony

Reputation: 67065

The problem is that you cannot bind to a static class as binding requires an instance of a class.

You can try a workaround like this SO question

Upvotes: 3

Related Questions