我想在页面上制作带有表格的布局。现在我有:
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<ScrollViewer Grid.Row="0" Margin="10,0,10,0">
<ListView
x:Name="NewsList"
HorizontalAlignment="Center">
<ListView.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<TextBlock Margin="15" Grid.Column="0" FontSize="25" Text="{Binding news_time}"/>
<TextBlock Margin="15" Grid.Column="1" FontSize="25" Text="{Binding title}"/>
<TextBlock Margin="15" Grid.Column="2" FontSize="25" Text="{Binding news_text}"/>
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</ScrollViewer>
</Grid>
我想对ObservableCollection
个对象进行绑定,以便动态地将Grid
行添加到StackPanel
个标记。这是我的.cs
文件。
public class News
{
public int id;
public string news_time;
public string title;
public string news_text;
}
public sealed partial class TermsAndNews : Page
{
public ObservableCollection<News> newsCollection { get; set; } =
new ObservableCollection<News>();
// ...
// Method called on initialization
private async void GetData()
{
var httpClient = new HttpClient();
var responsetNews = await httpClient.GetAsync("http://localhost:3000/news");
responsetNews.EnsureSuccessStatusCode();
string jsonNews = await responsetNews.Content.ReadAsStringAsync();
this.newsCollection = JsonConvert.DeserializeObject<ObservableCollection<News>>(jsonNews);
NewsList.ItemsSource = newsCollection;
}
}
运行代码后,不显示任何内容。有什么想法吗?
答案 0 :(得分:0)
尝试更改
this.newsCollection = .....
到
ObservableCollection<News> tempobcol = ...
然后迭代并添加到newsCollection
Foreach (News n in tempobcol)
{ newsCollection.Add(n); }
最后,删除
NewsList.ItemsSource = newsColleciton;
将其添加到XAML
<ListView x:Name:"NewsList" ItemsSource:="{Binding newsCollection}"...../>