2013-09-30 32 views
2

您好朋友,我通過使用ObservableCollectionasync方法在我的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"); 

    } 

我不明白爲什麼會發生這種情況。我錯過了這裏的一些概念,請告訴我..任何幫助或建議表示讚賞..

回答

2

你是缺乏從你的SomeCollection財產 - - this如何實現這一點財產變更事件射擊。

需要的原因是在分配DataContext屬性之前執行異步之前的FillCollection方法的一部分,並且在Web請求完成後另一半。因此,在你不工作的例子中,View不知道整個集合已被改變。

另一方面,考慮在每個列表刷新(你想刷新它在某個點?)上丟失ObservableCollection的新實例。該類的基礎是通過知道哪些元素被添加/移除/移動來提供UI方式來優化ItemsControl中的項目的刷新,如果您創建新的收集整個ListView將被重新渲染,這可能是昂貴的。我建議在FillCollection之前將您的任務移動到構造函數中,以便爲代碼清晰起見,並很好地處理內容更改 - 它對您更有用,但如果視圖複雜,則值得。