[Android] Allow Previewer to set a per-page Context (#1304)

* Allow previewer to set a per-page context

* Remove unnecessary using directive
This commit is contained in:
E.Z. Hart 2017-11-27 15:05:21 -07:00 коммит произвёл Rui Marinho
Родитель 22812e47a3
Коммит 53fb8a4465
1 изменённых файлов: 20 добавлений и 4 удалений

Просмотреть файл

@ -54,8 +54,6 @@ namespace Xamarin.Forms.Platform.Android
readonly bool _embedded;
internal Platform(Context context, bool embedded)
{
_embedded = embedded;
@ -305,7 +303,8 @@ namespace Xamarin.Forms.Platform.Android
[Obsolete("CreateRenderer(VisualElement) is obsolete as of version 2.5. Please use CreateRendererWithContext(VisualElement, Context) instead.")]
public static IVisualElementRenderer CreateRenderer(VisualElement element)
{
return CreateRenderer(element, Forms.Context);
// If there's a previewer context set, use that when created
return CreateRenderer(element, GetPreviewerContext(element) ?? Forms.Context);
}
internal static IVisualElementRenderer CreateRenderer(VisualElement element, Context context)
@ -1082,6 +1081,9 @@ namespace Xamarin.Forms.Platform.Android
#region Previewer Stuff
internal static readonly BindableProperty PageContextProperty =
BindableProperty.CreateAttached("PageContext", typeof(Context), typeof(Platform), null);
internal Platform(Context context) : this(context, false)
{
// we have this overload instead of using a default value for
@ -1090,7 +1092,21 @@ namespace Xamarin.Forms.Platform.Android
internal static void SetPageContext(BindableObject bindable, Context context)
{
// We need to keep this around for now because the previewer calls it
// Set a context for this page and its child controls
bindable.SetValue(PageContextProperty, context);
}
static Context GetPreviewerContext(Element element)
{
// Walk up the tree and find the Page this element is hosted in
Element parent = element;
while (!Application.IsApplicationOrNull(parent.RealParent))
{
parent = parent.RealParent;
}
// If a page is found, return the PageContext set by the previewer for that page (if any)
return (parent as Page)?.GetValue(PageContextProperty) as Context;
}
#endregion