你好朋友,我在我的 Windows 商店应用程序的异步方法中使用ObservableCollection遇到了非常奇怪的问题。我正在尝试在异步方法中的 ObservableCollection 中添加项目,如果我在 await 关键字所在的行上方定义 ObservableCollection 但我在此行下方初始化它不起作用,则它工作正常。我已经为这个问题制作了样本。我的xml代码是..
<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");
}
我不明白为什么会这样。我在这里遗漏了一些概念,请告诉我..任何帮助或建议表示赞赏..