【发布时间】: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