1

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();

    }

}
Ben
  • 1,113
  • 5
  • 15
  • 25

1 Answers1

2

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.

Community
  • 1
  • 1
BFree
  • 102,548
  • 21
  • 159
  • 201
  • In addition to that, it would be great if you would set it to be accessed via a DependencyProperty. – Den Feb 01 '11 at 21:47
  • No need to set it as a DP, since you probably never want to change ContactLists *instance* (only its contents) – Ana Betts Feb 02 '11 at 04:54