Reputation: 18799
I am building a Windows phone app using Xamarin in a portable class Library. I have got the Images from the Windows Phone Camera Roll and I am passing the List back to the PCL and assigning the Image to an ImageSource in my view.
Windows Phone Get Images:
foreach (var image in CameraRollPictures)
{
Image img = new Image();
img.Source = ImageSource.FromStream(() => image.GetImage());
images.Add(img);
}
return images;
PCL method:
private RelayCommand _importPhoto;
public RelayCommand ImportPhoto
{
get
{
return _importPhoto
?? (_importPhoto = new RelayCommand(
() =>
{
IOperations op = DependencyService.Get<IOperations>();
Task<List<Image>> t = new Task<List<Image>>(() =>
{
return op.ImportPhoto();
});
t.ContinueWith((sender) =>
{
PageOp.Navigate(new TaggingPage());
if (sender.Result.Count != 0)
{
try
{
App.Locator.TaggingPageVM.ImageSrc = sender.Result[0].Source;
}
catch (Exception ex)
{
}
}
}, TaskScheduler.FromCurrentSynchronizationContext());
t.Start();
}));
View:
<Image Source="{Binding ImageSrc}"/>
The Exception:
{System.UnauthorizedAccessException: Invalid cross-thread access.
at MS.Internal.XcpImports.CheckThread() at System.Windows.DependencyObject..ctor(UInt32 nativeTypeIndex, IntPtr constructDO) at System.Windows.Media.Imaging.BitmapImage..ctor()
at Xamarin.Forms.Platform.WinPhone.StreamImagesourceHandler.d__0.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult() at Xamarin.Forms.Platform.WinPhone.ImageRenderer.d__0.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.AsyncMethodBuilderCore.b__3(Object state)}
UPDATE
If I load a picture from a resource then it works fine.
App.Locator.TaggingPageVM.ImageSrc = ImageSource.FromFile("50175950-tulips-microsofts.jpg");
It must be an error to do with the images created on the windows phone and passing those images back to my PCL
Upvotes: 1
Views: 794
Reputation: 18799
I'm using Xamarin so:
Device.BeginInvokeOnMainThread(() => { App.Locator.TaggingPageVM.ImageSrc = sender.Result[0].Source; });
Fixed the Cross-Thread error
Upvotes: 1