wm1sr
wm1sr

Reputation: 2015

Binding a collection not working

I'm working on a Windows Phone app which has a ListBox with an ItemTemplate. I'm trying to bind an ObservableCollection of my ViewModel to this ListBox but nothing is being shown.

The XAML of this page looks like this:

...
<phone:PhoneApplicationPage.Resources>
    <DataTemplate x:Key="MyItemTemplate">
        <Grid Height="Auto" VerticalAlignment="Top" Width="Auto">
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto" />
                <RowDefinition Height="*" />
            </Grid.RowDefinitions>
            <TextBlock Text="{Binding Path=Name}" 
                       Style="{StaticResource PhoneTextLargeStyle}" 
                       Grid.Row="0"/>
            <TextBlock Text="{Binding Path=Description}" 
                       Style="{StaticResource PhoneTextSubtleStyle}" 
                       Grid.Row="1"/>
        </Grid>
    </DataTemplate>
</phone:PhoneApplicationPage.Resources>
...

<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
    <ListBox x:Name="myListBox" 
             ItemsSource="{Binding Path=MyItems, Mode=TwoWay}" 
             Margin="12, 0, 12, 0"
             ItemTemplate="{StaticResource MyItemTemplate}"/>
</Grid>
...

And here's the classes MyItem and MyViewModel which has the ObservableCollection I'm trying to bind to:

public class MyItem
{
    public string Name { get; set; }
    public string Description { get; set; }
}

public class MyViewModel
{
    public readonly ObservableCollection<MyItem> MyItems =
        new ObservableCollection<MyItem>();
}

I still have to implement the INotifyPropertyChanged interface.

And lastly, in the constructor of the page I set the DataContext to an instance of the ViewModel:

public MainPage() 
{
    MyViewModel viewModel = new MyViewModel();        

    viewModel.MyItems.Add(new MyItem() { Name = "1st", Description = "Description" });
    viewModel.MyItems.Add(new MyItem() { Name = "2nd", Description = "Description" });

    this.DataContext = viewModel;
}

That doesn't work. However, if I set the ItemsSource of the ListBox in code it works fine!

    myListBox.ItemsSource = viewModel;

So what am I missing here?

Upvotes: 1

Views: 65

Answers (1)

Rafal
Rafal

Reputation: 12619

Your MyItems is not a property so you cannot bind to it.

public class MyViewModel
{
    private readonly ObservableCollection<MyItem> _myItems =
        new ObservableCollection<MyItem>();

    public ObservableCollection<MyItem> MyItems { get{ return _myItems; } }
}

Try this. It will allow you to create one way binding as there is no setter available.

Upvotes: 2

Related Questions