Приветствую вас, я получаю очень странную проблему, используя ObservableCollection в async метод в моем приложении для Windows. Я пытаюсь добавить элементы в ObservableCollection в async-методе, он работает нормально, если я определяю 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");
}
Я не понимаю, почему это происходит. Я пропустил какую-то концепцию здесь, пожалуйста, скажите мне, что мне нравится какая-то помощь или предложение.