2012-11-29 32 views
5

我有一個自定義類Awaitable方法(簡化的東西,我已經剝離下來的代碼):在調用屬性訪問[Windows應用商店的應用程序/城域應用]

public class AlbumItem 
{ 
    public StorageFile AlbumThumbnail { get; set;} 
} 

當我結合這一個ListView:

<ListView.ItemTemplate> 
      <DataTemplate> 
       <Grid Height="100" Background="#FFabe372"> 
        <Grid.ColumnDefinitions> 
         <ColumnDefinition Width="80" /> 
         <ColumnDefinition Width="*" /> 
        </Grid.ColumnDefinitions> 
        <Image Source="{Binding AlbumSource}" Margin="10" Stretch="Uniform"></Image> 
        <TextBlock Margin="20 5" Grid.Column="1" Style="{StaticResource AlbumListViewItemStyle}" Text="{Binding AlbumDisplayText}"></TextBlock> 
       </Grid> 

      </DataTemplate> 
</ListView.ItemTemplate> 

Image的源設置爲AlbumSource,因爲我已經想實現AlbumSourceGet - 僅屬性:

public class AlbumItem 
{ 
    public StorageFile AlbumThumbnail { get; set;} 

    public BitmapImage AlbumSource 
    { 
     get 
     { 
      BitmapImage bmp = new BitmapImage(); 
      bmp.SetSource(await AlbumThumbnail.OpenReadAsync()); 
      return bmp; 
     } 
    } 
} 

正如預期的那樣,我不能在訪問器方法中使用await關鍵字,同時我無法將屬性存根聲明爲async方法。

有人能指出我正確的方向嗎?我稍後可能會嘗試Converter。謝謝!

回答

7

恕我直言屬性訪問器應該總是幾乎立即返回。長時間運行的操作不應該在屬性訪問器內部執行,因爲這可能會產生顯着的性能影響,因爲廣泛存在的假設是訪問器基本上是一個變量讀取操作(即,屬性可以循環訪問,不會爲後續訪問等緩存) )。

我會做這樣的事情:

private async Task SetAlbumSourceAsync() 
{ 
    bmp = new BitmapImage(); 
    var source = await AlbumThumbnail.OpenReadAsync(); 
    bmp.SetSource(source); 
    RaisePropertyChanged("AlbumSource"); 
} 

BitmapImage bmp; 
public BitmapImage AlbumSource 
{ 
    get 
    { 
     if (bmp == null) // might need a better sync mechanism to prevent reentrancy but you get the idea 
      SetAlbumSourceAsync(); 

     return bmp; 
    } 
} 
+0

謝謝!我明白了,但弗拉維恩的方法解決了我的迫切需求。我會探索你的方法,看看我能在這之後做好準備。 –

+2

+1這是更正確的答案。沒有技術上的理由說'異步'屬性不能存在;這是一個設計決定,因爲「異步屬性」違背了財產的概念。 –

+0

是的,我迄今爲止實現了我的屬性使用這種方法,是的,它不會嗆我的用戶界面!謝謝一堆! –

2

如果您使用await,返回類型將必須是Task<BitmapImage>。如果您希望能夠綁定到您的XAML,則需要返回BitmapImage,因此不能使用await。使用Task.Result來代替:

public BitmapImage AlbumSource 
{ 
    get 
    { 
     BitmapImage bmp = new BitmapImage(); 
     bmp.SetSource(AlbumThumbnail.OpenReadAsync().GetResults()); 
     return bmp; 
    } 
} 
+0

該方法解決了我的問題,雖然dkackman的回答給了我另一個層面都摸索,謝謝!但我不得不將'Task.Result'更改爲'Task.GetResults()'...並且我對'SetSource'上的語法錯誤不利(應該是'SetSource()')。 –

相關問題