From c98d338e15a29897e3a9a9d03d30dd3c70347925 Mon Sep 17 00:00:00 2001 From: "E.Z. Hart" Date: Thu, 7 Apr 2016 00:12:07 -0600 Subject: Force conversion to target type when Static Resource returns OnPlatform --- .../MarkupExtensions/StaticResourceExtension.cs | 29 +++++++++++++++++++--- 1 file changed, 26 insertions(+), 3 deletions(-) (limited to 'Xamarin.Forms.Xaml') diff --git a/Xamarin.Forms.Xaml/MarkupExtensions/StaticResourceExtension.cs b/Xamarin.Forms.Xaml/MarkupExtensions/StaticResourceExtension.cs index e5a7aef7..4f1465d3 100644 --- a/Xamarin.Forms.Xaml/MarkupExtensions/StaticResourceExtension.cs +++ b/Xamarin.Forms.Xaml/MarkupExtensions/StaticResourceExtension.cs @@ -1,4 +1,5 @@ using System; +using System.Reflection; namespace Xamarin.Forms.Xaml { @@ -32,13 +33,35 @@ namespace Xamarin.Forms.Xaml continue; object res; if (ve.Resources.TryGetValue(Key, out res)) - return res; + { + return ConvertCompiledOnPlatform(res); + } } if (Application.Current != null && Application.Current.Resources != null && Application.Current.Resources.ContainsKey(Key)) - return Application.Current.Resources[Key]; + { + var resource = Application.Current.Resources[Key]; + + return ConvertCompiledOnPlatform(resource); + } + + throw new XamlParseException($"StaticResource not found for key {Key}", xmlLineInfo); + } + + static object ConvertCompiledOnPlatform(object resource) + { + var actualType = resource.GetType(); + if (actualType.GetTypeInfo().IsGenericType && actualType.GetGenericTypeDefinition() == typeof(OnPlatform<>)) + { + // If we're accessing OnPlatform via a StaticResource in compiled XAML + // we'll have to handle the cast to the target type manually + // (Normally the compiled XAML handles this by calling `implicit` explicitly, + // but it doesn't know to do that when it's using a static resource) + var method = actualType.GetRuntimeMethod("op_Implicit", new[] { actualType }); + resource = method.Invoke(resource, new[] { resource }); + } - throw new XamlParseException(string.Format("StaticResource not found for key {0}", Key), xmlLineInfo); + return resource; } } } \ No newline at end of file -- cgit v1.2.3