Information
Quite simply, I’m attempting to create an app that would display the contacts for a user.
I’m also a self-taught programmer, so I
you can do one thing ..
you can retrieve all the images from the contacts class and store them in an array or stack or List of BitmapImages .. (*** i think list would be an better option )
Contact c = value as Contact;
foreach(var p in c)
{
q.Add(p.Thumbnail);
}
here q
is an list of bitmapmages
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;
}
The problem is that the GetImage method is asynchronous, so you need to wait for the result to complete:
Task<BitmapImage> getImageTask = GetImage(c);
getImageTask.RunSynchronously();
return getImageTask.Result;
Thanks to Romasz and Murven, I was able to get a solution for my problem.
XAML:
<ListView x:Name="ContactsView" Grid.Row="1" Background="White" ItemsSource="{Binding}">
<ListView.ItemTemplate>
<DataTemplate>
<Image x:Name="ContactImage" DataContext="{Binding Converter={StaticResource ContactPictureConverter}}" Source="{Binding Result}" Height="100" Width="100" Margin="0,0,0,0"/>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
Converter:
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<BitmapImage>(GetImage(c));
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
return null;
}
}
private async Task<BitmapImage> 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();
}
}
Packages:
Nito.AsyncEx from Nuget