您好朋友,我通過使用ObservableCollection在async方法在我的Windows應用商店應用程序中得到了很奇怪的問題。我正在嘗試添加ObservableCollection中的異步方法中的項目,它工作正常,如果我定義的ObservableCollection上面的一行,其中關鍵字是等待,但我初始化下面這行它不工作。我爲這個問題製作了樣本。 我的XAML代碼是..異步方法中的可觀察收集
<Page
x:Class="observableCollectionTest.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:observableCollectionTest"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
<ListView ItemsSource="{Binding SomeCollection}" Background="Pink" HorizontalAlignment="Left" Width="500" >
<ListView.ItemTemplate>
<DataTemplate>
<Grid Width="200" Height="200" Background="Red" >
<Button Content="click me" Name="btn" ></Button>
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Grid>
我的炫魅反手工作的代碼是..
public sealed partial class MainPage : Page
{
public ObservableCollection<string> SomeCollection { get; set; }
public MainPage()
{
this.InitializeComponent();
FillCollection();
this.DataContext = this;
}
public async Task FillCollection()
{
SomeCollection = new ObservableCollection<string>(); // it is working..
HttpClient client = new HttpClient();
HttpResponseMessage message = await client.GetAsync("https://www.google.co.in/");
SomeCollection.Add("asd");
SomeCollection.Add("asd");
SomeCollection.Add("asd");
SomeCollection.Add("asd");
SomeCollection.Add("asd");
SomeCollection.Add("asd");
SomeCollection.Add("asd");
SomeCollection.Add("asd");
SomeCollection.Add("asd");
SomeCollection.Add("asd");
}
我不工作炫魅反手FillCollection代碼..
public async Task FillCollection()
{
HttpClient client = new HttpClient();
HttpResponseMessage message = await client.GetAsync("https://www.google.co.in/");
SomeCollection = new ObservableCollection<string>(); // this is not working
SomeCollection.Add("asd");
SomeCollection.Add("asd");
SomeCollection.Add("asd");
SomeCollection.Add("asd");
SomeCollection.Add("asd");
SomeCollection.Add("asd");
SomeCollection.Add("asd");
SomeCollection.Add("asd");
SomeCollection.Add("asd");
SomeCollection.Add("asd");
}
我不明白爲什麼會發生這種情況。我錯過了這裏的一些概念,請告訴我..任何幫助或建議表示讚賞..