【发布时间】:2016-03-17 19:17:25
【问题描述】:
我在列表视图上使用 ObservableCollection。 ObservableCollection 使用异步方法从 Web 服务正确获取其数据,然后解析它并使用 NewsProxyParser(string thing, out ObservableCollection newsList) 方法上的 Add 方法填充 ObservableCollection,但我无法使用绑定 ObservableCollection。
我是 UWP 的新手,所以我认为异步方法在与 GUI 不同的线程上运行。如何正确绑定以使用从 Web 服务获取的数据更新 GUI?
我的 XAML:
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<ListView Name="ListViewNews" ItemsSource="{x:Bind NewsCollection, Mode=OneWay}" IsItemClickEnabled="True" ItemClick="ListView_ItemClick">
<ListView.ItemTemplate>
<DataTemplate x:DataType="data:News">
<RelativePanel Margin="0,16" >
<Image Name="x:Thumb" Source="{x:Bind thumbnailUrl}" Width="96" Height="96" RelativePanel.AlignLeftWithPanel="True" Margin="0,0,16,0"></Image>
<TextBlock Name="x:Title" Text="{x:Bind title}" FontSize="22" FontWeight="Bold" RelativePanel.RightOf="x:Thumb"></TextBlock>
<TextBlock Name="x:Date" Text="{x:Bind dateString}" FontSize="12" FontWeight="Light" Foreground="Gray" RelativePanel.RightOf="x:Thumb" RelativePanel.Below="x:Title"></TextBlock>
<TextBlock Name="x:Text" Text="{x:Bind newsText}" Foreground="Gray" RelativePanel.RightOf="x:Thumb" RelativePanel.Below="x:Date"></TextBlock>
</RelativePanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Grid>
还有cs:
public sealed partial class NewsPage : Page
{
private ObservableCollection<News> NewsCollection;
public NewsPage()
{
NewsRequest();
this.InitializeComponent();
}
private async void NewsRequest()
{
//Fetch News from web
string response = await NewsProxy.GetNews("TokenX");
//Parse News to add to NewsCollection
bool success = NewsProxy.NewsProxyParser(response, out NewsCollection);
// success is true and NewsCollection has new updated values
if (success)
{
News n = new News();
n.title = "Just to trigger collectionchanged";
n.newsText = "dadada";
n.order = 1;
NewsCollection.Add(n);
Debug.WriteLine("Still No GUI updated!!!");
}
}
}
【问题讨论】:
标签: c# win-universal-app observablecollection windows-10-universal