c# - 绑定(bind)集合不起作用

标签 c# xaml windows-phone-8 mvvm

我正在开发一个带有 ItemTemplate 的 ListBox 的 Windows Phone 应用程序。我正在尝试将我的 ViewModel 的 ObservableCollection 绑定(bind)到此 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>
...

这是我试图绑定(bind)到的具有 ObservableCollection 的 MyItem 和 MyViewModel 类:
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 接口(interface)。

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

那么我在这里错过了什么?

最佳答案

您的 MyItems不是一个属性,所以你不能绑定(bind)到它。

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

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

试试这个。它将允许您创建一种方式绑定(bind),因为没有可用的 setter 。

关于c# - 绑定(bind)集合不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24365601/

相关文章:

c# - 启动画面等待线程完成

c# - "..."的最佳重载匹配有一些无效参数

c# - Entity Framework 与.NET 4.0多对多关联

c# - 压缩图像大小或减小捕获图像的尺寸

xaml - LongListSelector 不滚动

c# - 测试泛型类型是否支持 ICloneable

c# - 手动制作WPF项目

wpf - 在文本框中添加前导 0

windows-phone-8 - 在 WP8 上实现滑动事件

windows-phone-8 - Microsoft.Smartdevice.Connectivity 和 Windows Phone 8,启动 native 应用程序,发送输入?