绑定集合不起作用

时间:2014-06-23 12:11:11

标签: c# xaml windows-phone-8 mvvm

我正在开发一个Windows Phone应用程序,它有一个带有ItemTemplate的ListBox。我正在尝试将我的ViewModel的ObservableCollection绑定到此ListBox,但没有显示任何内容。

此页面的XAML如下所示:

...
<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>
...

这里是MyItem和MyViewModel类,它们有我正在尝试绑定的ObservableCollection:

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

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

我仍然需要实现INotifyPropertyChanged接口。

最后,在页面的构造函数中,我将DataContext设置为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;
}

这不起作用。但是,如果我在代码中设置ListBox的ItemsSource,它可以正常工作!

    myListBox.ItemsSource = viewModel;

那我在这里错过了什么?

1 个答案:

答案 0 :(得分:2)

您的MyItems不是属性,因此您无法绑定它。

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

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

试试这个。它将允许您创建单向绑定,因为没有可用的setter。