Forms Previewer and Custom Controls

Recent versions of Xamarin include the Forms Previewer which generates a live representation of your XAML as it will appear on iOS or Android. I noticed one slight problem when working on my MediaElement control…

The Android renderer instantiates a MediaController object. This is a standard Android class but the Forms Previewer would throw an exception any time my control was placed on a page. The exception popup is not very friendly either – it truncates text and has no method to copy the text to the clipboard.

Forms Previewer Exception


I needed a way to determine if the code was running in the Forms Previewer and to just fake it and not create the native control. This will render a grey box for the MediaElement which frankly is fine with me to get the layout right. It turns out that in the absence of an IsDesignTime equivalent property there is a simple way to tell if your code is executing in a real app or not – and it’s the same as Silverlight (remember that?). Simply check if Application.Current is null inside the OnElementChanged method. If there is a current application you can render the control normally, if Current is null then don’t call the code to create the control.

if (Application.Current != null)
     // create native control here..

The iOS renderer also uses a native control (AVPlayerViewController) but doesn’t present the same issue so this workaround wasn’t necessary there.