WP8.1 C#绑定联系人图像

信息
很简单,我正在尝试创建一个可以显示用户联系人的应用程序。

我也是一个自学成才的程序员,所以我在某些方面有编程经验,但我对数据绑定一般都比较新。

首先,我有一个ListView控件,其中包含图像绑定。

       

我还有一个转换器,它获取Contact Image的IRandomAccessStream并将其作为BitmapImage返回。 如果未找到任何图像(nullexception),则转换器将返回联系人的默认图片。

 public class ContactPictureConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, string culture) { Contact c = value as Contact; try { return GetImage(c).Result; } catch (Exception ex) { Debug.WriteLine(ex.Message); } return @"Images/default.jpg"; } async Task GetImage(Contact con) { BitmapImage bitmapImage = new BitmapImage(); bitmapImage.DecodePixelHeight = 100; bitmapImage.DecodePixelWidth = 100; using (IRandomAccessStream fileStream = await con.Thumbnail.OpenReadAsync()) { await bitmapImage.SetSourceAsync(fileStream); } return bitmapImage; } public object ConvertBack(object value, Type targetType, object parameter, string culture) { throw new NotImplementedException(); } } 

附加信息
该应用程序设置为Windows Phone 8.1 WinRT。
为了获得联系人,我使用了ContactStore。

 IReadOnlyList contacts; //Global Declaration ContactStore store = await ContactManager.RequestStoreAsync(); contacts = await store.FindContactsAsync(); ContactsView.ItemsSource = contacts; 

问题
每个联系人都返回默认的联系人图像(意味着在尝试获取联系人图像时发生了一些exception)。 这不应该发生,因为我的大多数联系人都有与之关联的图像。


我应该如何获取联系人的图像并将其绑定到ListView for Windows Phone 8.1中的图像控件?

感谢Romasz和Murven,我能够为我的问题找到解决方案。

XAML:

        

转换器:

 using Nito.AsyncEx; public class ContactPictureConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, string language) { try { Contact c = value as Contact; return NotifyTaskCompletion.Create(GetImage(c)); } catch (Exception ex) { Debug.WriteLine(ex.Message); return null; } } private async Task GetImage(Contact con) { using (var stream = await con.Thumbnail.OpenReadAsync()) { BitmapImage image = new BitmapImage(); image.DecodePixelHeight = 100; image.DecodePixelWidth = 100; image.SetSource(stream); return image; } } public object ConvertBack(object value, Type targetType, object parameter, string culture) { throw new NotImplementedException(); } } 

包:
来自Nuget的Nito.AsyncEx

  public static BitmapImage GetImage(Contact con) { if (con == null || con.Thumbnail == null) { return null; } var bitmapImage = new BitmapImage(); bitmapImage.DecodePixelHeight = 256; bitmapImage.DecodePixelWidth = 256; Action load = async () => { using (IRandomAccessStream fileStream = await con.Thumbnail.OpenReadAsync()) { await bitmapImage.SetSourceAsync(fileStream); } }; load(); return bitmapImage; } 

问题是GetImage方法是异步的,因此您需要等待结果完成:

  Task getImageTask = GetImage(c); getImageTask.RunSynchronously(); return getImageTask.Result; 

你可以做一件事……

您可以从联系人类中检索所有图像并将它们存储在数组或堆栈或BitmapImages列表中。(***我认为列表将是更好的选择)

Contact c = value as Contact; foreach(var p in c) { q.Add(p.Thumbnail); }

这里qlist of bitmapmages