【问题标题】:How to instantiate xamarin android/ios native custom control class in xamarin forms xaml如何在 xamarin 表单 xaml 中实例化 xamarin android/ios 本机自定义控件类
【发布时间】:2015-05-13 00:14:31
【问题描述】:

自定义控件类:

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 平台特定的自定义控件。

【问题讨论】:

  • Xamarin.Forms 会将其控件(例如Entry)呈现为每个特定平台的本机控件,那么您的问题是什么?也许您正在 Xamarin.Forms 中寻找类似 Custome Renderers 的东西?
  • 没有。我需要呈现 Xamarin.Forms 中不可用的 android/ios 特定控件。
  • 我认为你不了解 Xamarin.Forms 的概念,请阅读它的工作原理以及为什么不应该关注 Xamarin.Forms 中的本机控件。

标签: xamarin.forms


【解决方案1】:

如果您使用的是 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
        }
    }
}

如果您发现单独呈现自定义控件不能提供您需要的确切控制级别,您还可以自定义PageRenderers,如here所示。

【讨论】:

    猜你喜欢
    • 2017-11-18
    • 1970-01-01
    • 1970-01-01
    • 2016-08-16
    • 2017-02-24
    • 2019-10-13
    • 1970-01-01
    • 1970-01-01
    • 2012-06-20
    相关资源
    最近更新 更多