Monday, May 18, 2015

Add ImageFailed and ImageOpened to the Xamarin Forms Image control

Currently the Image control in Xamarin Forms does not have an event to handle when image could or couldn't open.
I created a way to do this by extending the implementation for the Image control and ImageSource.
Check out the source code and a demo app on my GitHub:
I implemented two ways to handle image loaded status. You could either: 
1. Use the Image derived class ImageEx which exposes ImageOpened and ImageFailed events:
<controls:ImageEx Source="" ImageFailed="Image_ImageFailed" ImageOpened="Image_ImageOpened"/>

2. Handle the status change right on the ImageSource instance:
ImageSourceExtensions.SetStatusChangedHandler (MyImage.Source, (sender, status) => { Debug.WriteLine("Image status: {0}", status); });
where MyImage is an Image control in your Page

To add the implementation in your apps, you need to:

1. Add ImageSourceExtensions.cs and ImageEx.cs to your shared Xamarin Forms project

2. Add the ImageLoaderSourceHandlerEx.cs in your platform specific code




Few things you should be aware of:

- the events are called when Uri is valid. So for example, it will work when uri is “http://xxxxx’ but not for ‘xxxxx’
- when using the ImageSource.StatusChangedHandler note that the event is called only if you set the ImageSource to an Image. It doesn’t work if you just create an ImageSource using ImageSource.FromXXX methods. You must set the ImageSource to an Image.

No comments: