【问题标题】:Binding a collection not working绑定集合不起作用
【发布时间】:2014-06-23 12:11:11
【问题描述】:

我正在开发一个 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;

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

【问题讨论】:

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


    【解决方案1】:

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

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

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

    【讨论】:

    • 有效!因此 XAML 中的绑定仅适用于属性。我不知道。谢谢你的帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-21
    • 2011-03-30
    • 1970-01-01
    • 2016-10-03
    相关资源
    最近更新 更多