如何在xamarin表单xaml中实例化xamarin android / ios本机自定义控件类

时间:2015-03-11 09:25:07

标签: xamarin.forms

自定义控件类:

public class CustomTextInput : UITextField
    {

    }   

Xamarin.Forms xaml:

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:Custom="clr-namespace:SampleApp.CustomControls;assembly=SampleApp"
             x:Name="SampleAppView">
<ContentPage.Content>            
    <StackLayout Orientation="Horizontal">
        <Image Source="Sample_ic.png" WidthRequest="29" HeightRequest="29"/>
        <StackLayout Orientation="Vertical">
            <Label Text="Sample Text" TextColor="#717073" FontSize="Small" FontFamily="Helvetica"/>

            <!--Accessing IOS Custom control class-->
            <Custom:CustomTextInput Text="50 Gal"  BackgroundColor="Transparent" TextColor="#838288" />
        </StackLayout>  
    </StackLayout>
</ContentPage.Content>
</ContentPage>

我可以在xamarin.forms xaml中访问android / IOS自定义控件类吗?对于示例,我使用了 UITextField 控件。但是我需要访问xamarin.forms中没有的android / IOS平台特定的自定义控件。

1 个答案:

答案 0 :(得分:0)

如果您正在使用Xamarin.Forms,那么您正在使用独立于平台的控件。 UITextField不存在,而是映射到Entry

最好的办法是制作一个自定义的Entry子类:

public class MyEntry : Entry
{
}

并在你的XAML中使用它:

<?xml version="1.0" encoding="UTF-8"?>
<ContentPage 
    xmlns="http://xamarin.com/schemas/2014/forms" 
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" 
    x:Class="MyApp.SomePage"
    xmlns:local="clr-namespace:MyApp;assembly=MyApp">
    <local:MyEntry />
</ContentPage>

然后,在每个平台上,您都可以提供特定于平台的Renderer

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

            if (null == Control)
                return;

            var textField = Control as UITextField;

            // do stuff with textField
        }
    }
}

如果您发现单独呈现自定义控件并未提供所需的确切控制级别,您还可以自定义Page Renderers,如here所示。