Representadores personalizados de Xamarin.Forms ShellXamarin.Forms Shell Custom Renderers
Una de las ventajas de las aplicaciones de Xamarin.Forms Shell es que su apariencia y comportamiento es muy personalizable mediante las propiedades y los métodos que exponen las distintas clases de Shell.One of the advantages of Xamarin.Forms Shell applications is that their appearance and behavior is highly customizable through the properties and methods that the various Shell classes expose. Sin embargo, también es posible crear a un representador personalizado de Shell cuando se requieren personalizaciones más sofisticadas específicas de la plataforma.However, it's also possible to create a Shell custom renderer when more sophisticated platform-specific customizations are required. Al igual que con otros representadores personalizados, se puede agregar un representador personalizado de Shell a solo un proyecto de plataforma para personalizar la apariencia y el comportamiento, mientras se permite el comportamiento predeterminado en la otra plataforma; o se puede agregar un representador personalizado de Shell diferente a cada proyecto de plataforma para personalizar la apariencia y el comportamiento en iOS y Android.As with other custom renderers, a Shell custom renderer can be added to just one platform project to customize appearance and behavior, while allowing the default behavior on the other platform; or a different Shell custom renderer can be added to each platform project to customize appearance and behavior on both iOS and Android.
Las aplicaciones de Shell se representan mediante la clase ShellRenderer
en iOS y Android.Shell applications are rendered using the ShellRenderer
class on iOS and Android. En iOS, la clase ShellRenderer
se puede encontrar en el espacio de nombres Xamarin.Forms.Platform.iOS
.On iOS, the ShellRenderer
class can be found in the Xamarin.Forms.Platform.iOS
namespace. En Android, la clase ShellRenderer
se puede encontrar en el espacio de nombres Xamarin.Forms.Platform.Android
.On Android, the ShellRenderer
class can be found in the Xamarin.Forms.Platform.Android
namespace.
El proceso para crear un representador personalizado de Shell es el siguiente:The process for creating a Shell custom renderer is as follows:
- Cree la subclase de la clase
Shell
.Subclass theShell
class. Esta acción ya se realizará en la aplicación de Shell.This will already be accomplished in your Shell application. - Consuma la clase
Shell
en subclase.Consume the subclassedShell
class. Esta acción ya se realizará en la aplicación de Shell.This will already be accomplished in your Shell application. - Cree una clase de representador personalizado que se derive de la clase
ShellRenderer
, en las plataformas necesarias.Create a custom renderer class that derives from theShellRenderer
class, on the required platforms.
Creación de una clase de representador personalizadoCreate a custom renderer class
El proceso para crear una clase de representador personalizado de Shell es el siguiente:The process for creating a Shell custom renderer class is as follows:
- Se crea una subclase de la clase
ShellRenderer
.Create a subclass of theShellRenderer
class. - Invalide los métodos necesarios para llevar a cabo la personalización necesaria.Override the required methods to perform the required customization.
- Agregue un elemento
ExportRendererAttribute
a la subclaseShellRenderer
para especificar que se usará para representar la aplicación de Shell.Add anExportRendererAttribute
to theShellRenderer
subclass, to specify that it will be used to render the Shell application. Este atributo se usa para registrar al representador personalizado con Xamarin.Forms.This attribute is used to register the custom renderer with Xamarin.Forms.
Nota
Es opcional para proporcionar un representador personalizado de Shell en cada proyecto de plataforma.It's optional to provide a Shell custom renderer in each platform project. Si no está registrado un representador personalizado, se usará entonces la clase ShellRenderer
predeterminada.If a custom renderer isn't registered, then the default ShellRenderer
class will be used.
La clase ShellRenderer
expone los siguientes métodos reemplazables:The ShellRenderer
class exposes the following overridable methods:
iOSiOS | AndroidAndroid | UWPUWP |
---|---|---|
SetElementSize CreateFlyoutRenderer CreateNavBarAppearanceTracker CreatePageRendererTracker CreateShellFlyoutContentRenderer CreateShellItemRenderer CreateShellItemTransition CreateShellSearchResultsRenderer CreateShellSectionRenderer CreateTabBarAppearanceTracker Dispose OnCurrentItemChanged OnElementPropertyChanged OnElementSet UpdateBackgroundColor |
CreateFragmentForPage CreateShellFlyoutContentRenderer CreateShellFlyoutRenderer CreateShellItemRenderer CreateShellSectionRenderer CreateTrackerForToolbar CreateToolbarAppearanceTracker CreateTabLayoutAppearanceTracker CreateBottomNavViewAppearanceTracker OnElementPropertyChanged OnElementSet SwitchFragment Dispose |
CreateShellFlyoutTemplateSelector CreateShellHeaderRenderer CreateShellItemRenderer CreateShellSectionRenderer OnElementPropertyChanged OnElementSet UpdateFlyoutBackdropColor UpdateFlyoutBackgroundColor |
Las clases FlyoutItem
y TabBar
son alias de la clase ShellItem
, y la clase Tab
es un alias de la clase ShellSection
.The FlyoutItem
and TabBar
classes are aliases for the ShellItem
class, and the Tab
class is an alias for the ShellSection
class. Por lo tanto, el método CreateShellItemRenderer
se debe invalidar al crear un representador personalizado para objetos FlyoutItem
, y el método CreateShellSectionRenderer
se debe invalidar al crear un representador personalizado para objetos Tab
.Therefore, the CreateShellItemRenderer
method should be overridden when creating a custom renderer for FlyoutItem
objects, and the CreateShellSectionRenderer
method should be overridden when creating a custom renderer for Tab
objects.
Importante
Hay clases de representador adicionales de Shell, como ShellSectionRenderer
y ShellItemRenderer
, en iOS, Android y UWP.There are additional Shell renderer classes, such as ShellSectionRenderer
and ShellItemRenderer
, on iOS, Android, and UWP. Sin embargo, estas clases de representador adicionales se crean mediante invalidaciones en la clase ShellRenderer
.However, these additional renderer classes are created by overrides in the ShellRenderer
class. Por lo tanto, para personalizar el comportamiento de estas clases de representador adicionales, puede crear una subclase de ellas y una instancia de la subclase en la invalidación adecuada de la clase ShellRenderer
en subclase.Therefore, customizing the behavior of these additional renderer classes can be achieved by subclassing them, and creating an instance of the subclass in the appropriate override in the subclassed ShellRenderer
class.
Ejemplo de iOSiOS example
En el ejemplo de código siguiente se muestra una clase ShellRenderer
en subclase para iOS, que establece una imagen de fondo en la barra de navegación de la aplicación de Shell:The following code example shows a subclassed ShellRenderer
, for iOS, that sets a background image on the navigation bar of the Shell application:
using UIKit;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;
[assembly: ExportRenderer(typeof(Xaminals.AppShell), typeof(Xaminals.iOS.MyShellRenderer))]
namespace Xaminals.iOS
{
public class MyShellRenderer : ShellRenderer
{
protected override IShellSectionRenderer CreateShellSectionRenderer(ShellSection shellSection)
{
var renderer = base.CreateShellSectionRenderer(shellSection);
if (renderer != null)
{
(renderer as ShellSectionRenderer).NavigationBar.SetBackgroundImage(UIImage.FromFile("monkey.png"), UIBarMetrics.Default);
}
return renderer;
}
}
}
La clase MyShellRenderer
invalida el método CreateShellSectionRenderer
y recupera el representador creado por la clase base.The MyShellRenderer
class overrides the CreateShellSectionRenderer
method, and retrieves the renderer created by the base class. Luego, modifica al representador mediante el establecimiento de una imagen de fondo en la barra de navegación, antes de volver al representador.It then modifies the renderer by setting a background image on the navigation bar, before returning the renderer.
Ejemplo de AndroidAndroid example
En el ejemplo de código siguiente se muestra una clase ShellRenderer
en subclase para Android, que establece una imagen de fondo en la barra de navegación de la aplicación de Shell:The following code example shows a subclassed ShellRenderer
, for Android, that sets a background image on the navigation bar of the Shell application:
using Android.Content;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;
[assembly: ExportRenderer(typeof(Xaminals.AppShell), typeof(Xaminals.Droid.MyShellRenderer))]
namespace Xaminals.Droid
{
public class MyShellRenderer : ShellRenderer
{
public MyShellRenderer(Context context) : base(context)
{
}
protected override IShellToolbarAppearanceTracker CreateToolbarAppearanceTracker()
{
return new MyShellToolbarAppearanceTracker(this);
}
}
}
La clase MyShellRenderer
invalida el método CreateToolbarAppearanceTracker
y devuelve una instancia de la clase MyShellToolbarAppearanceTracker
.The MyShellRenderer
class overrides the CreateToolbarAppearanceTracker
method, and returns an instance of the MyShellToolbarAppearanceTracker
class. La clase MyShellToolbarAppearanceTracker
, que se deriva de la clase ShellToolbarAppearanceTracker
, se muestra en el ejemplo siguiente:The MyShellToolbarAppearanceTracker
class, which derives from the ShellToolbarAppearanceTracker
class, is shown in the following example:
using AndroidX.AppCompat.Widget;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;
namespace Xaminals.Droid
{
public class MyShellToolbarAppearanceTracker : ShellToolbarAppearanceTracker
{
public MyShellToolbarAppearanceTracker(IShellContext context) : base(context)
{
}
public override void SetAppearance(Toolbar toolbar, IShellToolbarTracker toolbarTracker, ShellAppearance appearance)
{
base.SetAppearance(toolbar, toolbarTracker, appearance);
toolbar.SetBackgroundResource(Resource.Drawable.monkey);
}
}
}
La clase MyShellToolbarAppearanceTracker
invalida el método SetAppearance
y modifica la barra de herramientas mediante el establecimiento de una imagen de fondo en ella.The MyShellToolbarAppearanceTracker
class overrides the SetAppearance
method, and modifies the toolbar by setting a background image on it.
Importante
Solo es necesario agregar el objeto ExportRendererAttribute
a un representador personalizado que se deriva de la clase ShellRenderer
.It's only necessary to add the ExportRendererAttribute
to a custom renderer that derives from the ShellRenderer
class. Se crean clases de representador de Shell en subclase adicionales mediante la clase ShellRenderer
en subclase.Additional subclassed Shell renderer classes are created by the subclassed ShellRenderer
class.