自定义 EntryCustomizing an Entry

下载示例 下载示例Download Sample Download the sample

Xamarin.Forms Entry 控件允许对单行文本进行编辑。本文演示了如何为 Entry 控件创建自定义呈现器,使开发人员能够使用自己特定于平台的自定义呈现替代默认本机呈现。_The Xamarin.Forms Entry control allows a single line of text to be edited. This article demonstrates how to create a custom renderer for the Entry control, enabling developers to override the default native rendering with their own platform-specific customization.

每个 Xamarin.Forms 控件都有一个附带的呈现器,适用于创建本机控件实例的各个平台。Every Xamarin.Forms control has an accompanying renderer for each platform that creates an instance of a native control. Xamarin.Forms 应用程序呈现 Entry 控件时,在 iOS 中实例化 EntryRenderer 类,进而实例化本机 UITextField 控件。When an Entry control is rendered by a Xamarin.Forms application, in iOS the EntryRenderer class is instantiated, which in turns instantiates a native UITextField control. 在 Android 平台上,EntryRenderer 类实例化 EditText 控件。On the Android platform, the EntryRenderer class instantiates an EditText control. 在通用 Windows 平台 (UWP) 上,EntryRenderer 类实例化 TextBox 控件。On the Universal Windows Platform (UWP), the EntryRenderer class instantiates a TextBox control. 有关 Xamarin.Forms 控件映射到的呈现器和本机控件类的详细信息,请参阅呈现器基类和本机控件For more information about the renderer and native control classes that Xamarin.Forms controls map to, see Renderer Base Classes and Native Controls.

下图说明了 Entry 控件和实现它的相应本机控件之间的关系:The following diagram illustrates the relationship between the Entry control and the corresponding native controls that implement it:

通过在每个平台上为 Entry 控件创建自定义呈现器,可以利用呈现过程来实现特定于平台的自定义。The rendering process can be taken advantage of to implement platform-specific customizations by creating a custom renderer for the Entry control on each platform. 执行此操作的过程如下:The process for doing this is as follows:

  1. 创建 Xamarin.Forms 自定义控件。Create a Xamarin.Forms custom control.
  2. 使用 Xamarin.Forms 中的自定义控件。Consume the custom control from Xamarin.Forms.
  3. 在每个平台上为控件创建自定义呈现器。Create the custom renderer for the control on each platform.

现在将依次讨论每个项,以在每个平台上实现具有不同背景颜色的 Entry 控件。Each item will now be discussed in turn, to implement an Entry control that has a different background color on each platform.

重要

本文介绍如何创建简单的自定义呈现器。This article explains how to create a simple custom renderer. 但是,要在每个平台上实现具有不同背景色的 Entry,无需创建自定义呈现器。However, it's not necessary to create a custom renderer to implement an Entry that has a different background color on each platform. 这可以通过使用 Device 类或 OnPlatform 标记扩展来轻松实现,以提供特定于平台的值。This can be more easily accomplished by using the Device class, or the OnPlatform markup extension, to provide platform-specific values. 有关详细信息,请参阅提供特定于平台的值OnPlatform 标记扩展For more information, see Providing Platform-Specific Values and OnPlatform Markup Extension.

创建自定义 Entry 控件Creating the Custom Entry Control

通过子类化 Entry 控件,可以创建自定义 Entry 控件,如以下示例代码所示:A custom Entry control can be created by subclassing the Entry control, as shown in the following code example:

public class MyEntry : Entry
{
}

MyEntry 控件创建在 .NET Standard 库项目中,并且只是 Entry 控件。The MyEntry control is created in the .NET Standard library project and is simply an Entry control. 将在自定义呈现器中进行控件自定义,因此 MyEntry 控件中无需任何其他实现。Customization of the control will be carried out in the custom renderer, so no additional implementation is required in the MyEntry control.

使用自定义控件Consuming the Custom Control

通过在控件元素上声明 MyEntry 自定义控件位置的命名空间并使用命名空间前缀,可以在 .NET Standard 库项目的 XAML 中引用该控件。The MyEntry control can be referenced in XAML in the .NET Standard library project by declaring a namespace for its location and using the namespace prefix on the control element. 下面的代码示例演示 XAML 页可以如何使用 MyEntry 控件:The following code example shows how the MyEntry control can be consumed by a XAML page:

<ContentPage ...
    xmlns:local="clr-namespace:CustomRenderer;assembly=CustomRenderer"
    ...>
    ...
    <local:MyEntry Text="In Shared Code" />
    ...
</ContentPage>

local 命名空间前缀可以命名为任何内容。The local namespace prefix can be named anything. 但是,clr-namespaceassembly 值必须与自定义控件的详细信息相匹配。However, the clr-namespace and assembly values must match the details of the custom control. 声明命名空间后,前缀用于引用自定义控件。Once the namespace is declared the prefix is used to reference the custom control.

下面的代码示例演示 C# 页可以如何使用 MyEntry 控件:The following code example shows how the MyEntry control can be consumed by a C# page:

public class MainPage : ContentPage
{
  public MainPage ()
  {
    Content = new StackLayout {
      Children = {
        new Label {
          Text = "Hello, Custom Renderer !",
        },
        new MyEntry {
          Text = "In Shared Code",
        }
      },
      VerticalOptions = LayoutOptions.CenterAndExpand,
      HorizontalOptions = LayoutOptions.CenterAndExpand,
    };
  }
}

此代码实例化新的 ContentPage 对象,该对象将在页面上垂直居中以及水平居中显示 LabelMyEntry 控件。This code instantiates a new ContentPage object that will display a Label and MyEntry control centered both vertically and horizontally on the page.

现在可以向每个应用程序项目添加自定义呈现器,以便在每个平台上自定义控件外观。A custom renderer can now be added to each application project to customize the control's appearance on each platform.

在每个平台上创建自定义呈现器Creating the Custom Renderer on each Platform

创建自定义呈现器类的过程如下所示:The process for creating the custom renderer class is as follows:

  1. 创建呈现本机控件的 EntryRenderer 类的子类。Create a subclass of the EntryRenderer class that renders the native control.
  2. 替代呈现本机控件的 OnElementChanged 方法并写入逻辑以自定义控件。Override the OnElementChanged method that renders the native control and write logic to customize the control. 创建相应的 Xamarin.Forms 控件时将调用此方法。This method is called when the corresponding Xamarin.Forms control is created.
  3. 向自定义呈现器类添加 ExportRenderer 属性,以指定其将用于呈现 Xamarin.Forms 控件。Add an ExportRenderer attribute to the custom renderer class to specify that it will be used to render the Xamarin.Forms control. 此属性用于向 Xamarin.Forms 注册自定义呈现器。This attribute is used to register the custom renderer with Xamarin.Forms.

备注

可选择在每个平台项目中提供自定义呈现器。It is optional to provide a custom renderer in each platform project. 如果未注册自定义呈现器,将使用控件基类的默认呈现器。If a custom renderer isn't registered, then the default renderer for the control's base class will be used.

下图说明了示例应用程序中每个项目的职责,以及它们之间的关系:The following diagram illustrates the responsibilities of each project in the sample application, along with the relationships between them:

MyEntry 控件由平台特定的 MyEntryRenderer 类呈现,这些类均派生自各平台的 EntryRenderer 类。The MyEntry control is rendered by platform-specific MyEntryRenderer classes, which all derive from the EntryRenderer class for each platform. 这导致每个 MyEntry 控件都使用特定于平台的背景色呈现,如下面的屏幕截图所示:This results in each MyEntry control being rendered with a platform-specific background color, as shown in the following screenshots:

EntryRenderer 类公开 OnElementChanged 方法,创建 Xamarin.Forms 控件时调用此方法以呈现相应的本机控件。The EntryRenderer class exposes the OnElementChanged method, which is called when the Xamarin.Forms control is created to render the corresponding native control. 此方法采用 ElementChangedEventArgs 参数,其中包含 OldElementNewElement 属性。This method takes an ElementChangedEventArgs parameter that contains OldElement and NewElement properties. 这两个属性分别表示呈现器“曾经”附加到的 Xamarin.Forms 元素和呈现器“现在”附加到的 Xamarin.Forms 元素 。These properties represent the Xamarin.Forms element that the renderer was attached to, and the Xamarin.Forms element that the renderer is attached to, respectively. 在示例应用程序中,OldElement 属性将为 null,且 NewElement 属性将包含对 MyEntry 控件的引用。In the sample application the OldElement property will be null and the NewElement property will contain a reference to the MyEntry control.

MyEntryRenderer 类中 OnElementChanged 方法的替代版本可执行本机控件自定义。An overridden version of the OnElementChanged method in the MyEntryRenderer class is the place to perform the native control customization. 可以通过 Control 属性访问平台上使用的对本机控件的类型化引用。A typed reference to the native control being used on the platform can be accessed through the Control property. 此外,可以通过 Element 属性获取对正在呈现的 Xamarin.Forms 控件的引用,尽管它没有在示例应用程序中使用。In addition, a reference to the Xamarin.Forms control that's being rendered can be obtained through the Element property, although it's not used in the sample application.

每个自定义呈现器类均用 ExportRenderer 属性修饰,该属性向 Xamarin.Forms 注册呈现器。Each custom renderer class is decorated with an ExportRenderer attribute that registers the renderer with Xamarin.Forms. 属性采用两个参数 - 正在呈现的 Xamarin.Forms 控件的类型名称和自定义呈现器的类型名称。The attribute takes two parameters – the type name of the Xamarin.Forms control being rendered, and the type name of the custom renderer. 属性的 assembly 前缀指示属性适用于整个程序集。The assembly prefix to the attribute specifies that the attribute applies to the entire assembly.

以下各部分讨论每个平台特定的 MyEntryRenderer 自定义呈现器类的实现。The following sections discuss the implementation of each platform-specific MyEntryRenderer custom renderer class.

在 iOS 上创建自定义呈现器Creating the Custom Renderer on iOS

以下代码示例展示了适用于 iOS 平台的自定义呈现器:The following code example shows the custom renderer for the iOS platform:

using Xamarin.Forms.Platform.iOS;

[assembly: ExportRenderer (typeof(MyEntry), typeof(MyEntryRenderer))]
namespace CustomRenderer.iOS
{
    public class MyEntryRenderer : EntryRenderer
    {
        protected override void OnElementChanged (ElementChangedEventArgs<Entry> e)
        {
            base.OnElementChanged (e);

            if (Control != null) {
                // do whatever you want to the UITextField here!
                Control.BackgroundColor = UIColor.FromRGB (204, 153, 255);
                Control.BorderStyle = UITextBorderStyle.Line;
            }
        }
    }
}

对基类的 OnElementChanged 方法的调用实例化 iOS UITextField 控件,并且将对控件的引用分配给呈现器的 Control 属性。The call to the base class's OnElementChanged method instantiates an iOS UITextField control, with a reference to the control being assigned to the renderer's Control property. 然后,使用 UIColor.FromRGB 方法将背景色设置为淡紫色。The background color is then set to light purple with the UIColor.FromRGB method.

在 Android 上创建自定义呈现器Creating the Custom Renderer on Android

以下代码示例展示了适用于 Android 平台的自定义呈现器:The following code example shows the custom renderer for the Android platform:

using Xamarin.Forms.Platform.Android;

[assembly: ExportRenderer(typeof(MyEntry), typeof(MyEntryRenderer))]
namespace CustomRenderer.Android
{
    class MyEntryRenderer : EntryRenderer
    {
        public MyEntryRenderer(Context context) : base(context)
        {
        }

        protected override void OnElementChanged(ElementChangedEventArgs<Entry> e)
        {
            base.OnElementChanged(e);

            if (Control != null)
            {
                Control.SetBackgroundColor(global::Android.Graphics.Color.LightGreen);
            }
        }
    }
}

对基类的 OnElementChanged 方法的调用实例化 Android EditText 控件,并且将对控件的引用分配给呈现器的 Control 属性。The call to the base class's OnElementChanged method instantiates an Android EditText control, with a reference to the control being assigned to the renderer's Control property. 然后,使用 Control.SetBackgroundColor 方法将背景色设置为淡绿色。The background color is then set to light green with the Control.SetBackgroundColor method.

在 UWP 上创建自定义呈现器Creating the Custom Renderer on UWP

以下代码示例展示了适用于 UWP 的自定义呈现器:The following code example shows the custom renderer for UWP:

[assembly: ExportRenderer(typeof(MyEntry), typeof(MyEntryRenderer))]
namespace CustomRenderer.UWP
{
    public class MyEntryRenderer : EntryRenderer
    {
        protected override void OnElementChanged(ElementChangedEventArgs<Entry> e)
        {
            base.OnElementChanged(e);

            if (Control != null)
            {
                Control.Background = new SolidColorBrush(Colors.Cyan);
            }
        }
    }
}

对基类的 OnElementChanged 方法的调用实例化 TextBox 控件,并且将对控件的引用分配给呈现器的 Control 属性。The call to the base class's OnElementChanged method instantiates a TextBox control, with a reference to the control being assigned to the renderer's Control property. 然后通过创建 SolidColorBrush 实例将背景色设置为蓝绿色。The background color is then set to cyan by creating a SolidColorBrush instance.

总结Summary

本文演示了如何创建 Xamarin.Forms Entry 控件的自定义控件呈现器,使开发人员能够使用自己特定于平台的呈现替代默认本机呈现。This article has demonstrated how to create a custom control renderer for the Xamarin.Forms Entry control, enabling developers to override the default native rendering with their own platform-specific rendering. 自定义呈现器提供了用于自定义 Xamarin.Forms 控件外观的一种强大方法。Custom renderers provide a powerful approach to customizing the appearance of Xamarin.Forms controls. 可使用它们进行细微的样式更改,也可进行复杂的特定于平台的布局和行为自定义。They can be used for small styling changes or sophisticated platform-specific layout and behavior customization.