Ben
Ben

Reputation: 1153

Binding ObervableCollection to ListBox

I have the following code that should display some information about ContactLists in a ListBox but there seems to be a problem with the binding as nothing is displayed. What am I missing? Would appreciate any help. Thanks!

XAML

</Window>
<Window.Resources>
<DataTemplate x:Key="ContactsTemplate">
        <WrapPanel>
            <TextBlock TextWrapping="Wrap" 
                       Text="{Binding ContactListName, Mode=Default}"/>
        </WrapPanel>
    </DataTemplate>

</Window.Resources>

<Grid x:Name="LayoutRoot" 
      Background="#FFCBD5E6">
    <Grid.DataContext>
        <local:MyViewModel/>
    </Grid.DataContext>

    <ListBox x:Name="contactsList"
             SelectionMode="Extended"
             Margin="7,8,0,35" 
             ItemsSource="{Binding ContactLists}" 
             ItemTemplate="{DynamicResource ContactsTemplate}" 
             HorizontalAlignment="Left" 
             Width="178" 
             SelectionChanged="contactsList_SelectionChanged"/>
</Grid>
</Window>

ViewModel

public class MyViewModel
{
    public ObservableCollection<ContactListModel> ContactLists;

    public MyViewModel()
    {
        var data = new ContactListDataAccess();
        ContactLists = data.GetContacts();

    }

}

Upvotes: 1

Views: 142

Answers (1)

BFree
BFree

Reputation: 103742

Change ContactLists to be a property for the binding to work correctly:

public class MyViewModel
{
    public ObservableCollection<ContactListModel> ContactLists{get;set;}

    public MyViewModel()
    {
        var data = new ContactListDataAccess();
        ContactLists = data.GetContacts();

    }
}

See here for more info.

Upvotes: 2

Related Questions