【发布时间】:2016-12-19 23:40:53
【问题描述】:
我有这个页面:NewsPage
<Page
x:Class="TouchTypeRacing.Views.NewsPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:TouchTypeRacing.Views"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:controls="using:TouchTypeRacing.Controls"
xmlns:models="using:TouchTypeRacing.Models"
DataContext="{Binding}"
mc:Ignorable="d">
<Grid Background="White">
....
<ScrollViewer Grid.Row="1"
VerticalScrollBarVisibility="Auto"
Margin="5,10,5,0">
<ItemsControl ItemsSource="{Binding Posts}"
x:Name="itemsControl">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Vertical"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate x:DataType="models:Post">
<controls:Post/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</ScrollViewer>
</Grid>
</Page>
页面的数据上下文绑定到视图模型。 PageViewmModelItemsControl 数据模板是 Post 控件。
页面上ItemsControl 的ItemsSource 绑定到viewmodel 的Posts 属性。
public NewsPage()
{
this.InitializeComponent();
_viewModel = new NewsPageViewModel();
DataContext = _viewModel;
}
然后,视图模型:
public class NewsPageViewModel
{
private ObservableCollection<Post> _posts = new ObservableCollection<Post>();
public ObservableCollection<Post> Posts { get { return _posts; } }
public NewsPageViewModel()
{
GetPosts(_posts);
}
public static void GetPosts(ObservableCollection<Post> posts)
{
posts.Clear();
posts = new ObservableCollection<Post>
{
new Post
{
Id = "1",
DateTime = DateTime.Today,
User = Application.CurrentUser,
Likes = 10,
ImagePath = Application.CurrentUser.ImagePath,
Message = "Test message",
Comments = new ObservableCollection<Comment>
{
new Comment {Id= "1", Content="Comment1", User = Application.CurrentUser },
new Comment {Id= "2", Content="Comment2", User = Application.CurrentUser },
new Comment {Id= "3", Content="Comment3", User = Application.CurrentUser },
new Comment {Id= "4", Content="Comment4", User = Application.CurrentUser },
},
Last2Comments = new List<Comment>
{
new Comment {Id= "3", Content="Comment3", User = Application.CurrentUser },
new Comment {Id= "4", Content="Comment4", User = Application.CurrentUser },
}
}
};
}
ItemsControl 显示为空。
我做错了什么?
【问题讨论】:
标签: c# wpf data-binding uwp uwp-xaml