【问题标题】:Custom entry null xamarin自定义条目 null xamarin
【发布时间】:2020-01-02 19:49:22
【问题描述】:

我在我的登录页面中创建了一个自定义条目,但它变为空 我刚刚创建了 hte CustomEntry 类和 CustomEntryRenderer,并将其放入 xaml 文件中

我的登录页面 .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"
             xmlns:custom="clr-namespace:HCTaNaMao.Customs"
             x:Class="HCTaNaMao.Views.Login">


    <ContentPage.Content>
        <StackLayout VerticalOptions="FillAndExpand" Padding="0,100,0,0">
            <Image Source="HCbackground.png" VerticalOptions="Center" HeightRequest="200" />
            <Label Text="Usuario" HorizontalTextAlignment="Center"/>

            <custom:CustomEntry
                                x:Name=" usernameEntry"
                                CornerRadius="18"
                                IsCurvedCornersEnabled="True"
                                BorderColor="LightBlue"    
                                HorizontalTextAlignment="Start"
                                FontSize="17"
                                HeightRequest="40"
                                Placeholder="Usuário"
                                PlaceholderColor="LightGray"
                                TextColor="Black"
                                FontAttributes="Bold"
                                WidthRequest="100"/>
            <Label Text="Senha"  HorizontalTextAlignment="Center"/>
            <custom:CustomEntry
                                x:Name=" passwordEntry"
                                CornerRadius="18"
                                IsCurvedCornersEnabled="True"
                                BorderColor="LightBlue"    
                                HorizontalTextAlignment="Start"
                                FontSize="17"
                                HeightRequest="40"
                                Placeholder="Senha"
                                PlaceholderColor="LightGray"
                                TextColor="Black"
                                FontAttributes="Bold"
                                WidthRequest="100"
                                IsPassword="True"/>
            <Button Text="Entrar" TextColor="White" Clicked="LoginUser" WidthRequest="110" 
            HorizontalOptions="Center" BackgroundColor="SteelBlue" BorderRadius="20"/>
            <Label x:Name="messageLabel" />
        </StackLayout>
    </ContentPage.Content>
</ContentPage>

我的登录页面 .xaml.cs

namespace HCTaNaMao.Views
{
    public partial class Login : ContentPage
    {
        public static int seq_cliente;
        public Login ()
        {
            InitializeComponent ();
usernameEntry.ReturnCommand = new Command(() => passwordEntry.Focus());
        }

        async void LoginUser(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(usernameEntry.Text) || string.IsNullOrEmpty(passwordEntry.Text))
            {
                if (string.IsNullOrEmpty(usernameEntry.Text))
                    await DisplayAlert("Usuario", "Digite o Usuario", "OK");
                else
                    await DisplayAlert("Senha", "Digite a Senha", "OK");
                return;
            }
            HCTMWebService service = new HCTMWebService();
            seq_cliente = service.Login(usernameEntry.Text.ToUpper());

            if (seq_cliente > 0)
                await Navigation.PopModalAsync();
            else
                await DisplayAlert("Erro Login", "Usuario ou Senha errado", "OK");
        }

        protected override bool OnBackButtonPressed()
        {
            #if __ANDROID__
                Android.OS.Process.KillProcess(Android.OS.Process.MyPid());
            #endif

            return base.OnBackButtonPressed();
        }


    }
}

我的自定义条目

namespace HCTaNaMao.Customs
{
    public class CustomEntry : Entry
    {
        public static readonly BindableProperty BorderColorProperty =
        BindableProperty.Create(
            nameof(BorderColor),
            typeof(Color),
            typeof(CustomEntry),
            Color.Gray);

        // Gets or sets BorderColor value
        public Color BorderColor
        {
            get { return (Color)GetValue(BorderColorProperty); }
            set { SetValue(BorderColorProperty, value); }
        }


        public static readonly BindableProperty BorderWidthProperty =
        BindableProperty.Create(
            nameof(BorderWidth),
            typeof(int),
            typeof(CustomEntry),
            Device.OnPlatform<int>(1, 2, 2));

        // Gets or sets BorderWidth value
        public int BorderWidth
        {
            get { return (int)GetValue(BorderWidthProperty); }
            set { SetValue(BorderWidthProperty, value); }
        }


        public static readonly BindableProperty CornerRadiusProperty =
        BindableProperty.Create(
            nameof(CornerRadius),
            typeof(double),
            typeof(CustomEntry),
            Device.OnPlatform<double>(6, 7, 7));

        // Gets or sets CornerRadius value
        public double CornerRadius
        {
            get { return (double)GetValue(CornerRadiusProperty); }
            set { SetValue(CornerRadiusProperty, value); }
        }


        public static readonly BindableProperty IsCurvedCornersEnabledProperty =
        BindableProperty.Create(
            nameof(IsCurvedCornersEnabled),
            typeof(bool),
            typeof(CustomEntry),
            true);

        // Gets or sets IsCurvedCornersEnabled value
        public bool IsCurvedCornersEnabled
        {
            get { return (bool)GetValue(IsCurvedCornersEnabledProperty); }
            set { SetValue(IsCurvedCornersEnabledProperty, value); }
        }

    }
}

我的渲染器

[assembly: ExportRenderer(typeof(CustomEntry), typeof(CustomEntryRenderer))]
namespace HCTaNaMao.Droid
{
    public class CustomEntryRenderer : EntryRenderer
    {
        public CustomEntryRenderer(Context context) : base(context)
        {
        }

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

            if (e.NewElement != null)
            {
                var view = (CustomEntry)Element;

                if (view.IsCurvedCornersEnabled)
                {
                    // creating gradient drawable for the curved background
                    var _gradientBackground = new GradientDrawable();
                    _gradientBackground.SetShape(ShapeType.Rectangle);
                    _gradientBackground.SetColor(view.BackgroundColor.ToAndroid());

                    // Thickness of the stroke line
                    _gradientBackground.SetStroke(view.BorderWidth, view.BorderColor.ToAndroid());

                    // Radius for the curves
                    _gradientBackground.SetCornerRadius(
                        DpToPixels(this.Context,
                            Convert.ToSingle(view.CornerRadius)));

                    // set the background of the label
                    Control.SetBackground(_gradientBackground);
                }

                // Set padding for the internal text from border
                Control.SetPadding(
                    (int)DpToPixels(this.Context, Convert.ToSingle(12)),
                    Control.PaddingTop,
                    (int)DpToPixels(this.Context, Convert.ToSingle(12)),
                    Control.PaddingBottom);
            }
        }
        public static float DpToPixels(Context context, float valueInDp)
        {
            DisplayMetrics metrics = context.Resources.DisplayMetrics;
            return TypedValue.ApplyDimension(ComplexUnitType.Dip, valueInDp, metrics);
        }
    }
}

在我的 Login.xaml.cs 中,行

usernameEntry.ReturnCommand = new Command(() => passwordEntry.Focus());

因为 usernameEntry 为空而出错

我必须实例化它吗?

【问题讨论】:

    标签: xamarin xamarin.forms xamarin.android xamarin.ios


    【解决方案1】:

    您需要在添加命令之前实例化您的自定义条目。自定义条目的正确使用方式基本如下:

    添加 StackLayouts 或其他内容布局

    <StackLayout VerticalOptions="FillAndExpand" Padding="0,100,0,0">
        <Image Source="HCbackground.png" VerticalOptions="Center" HeightRequest="200" />
        <Label Text="Usuario" HorizontalTextAlignment="Center"/>
    
        <StackLayout x:Name="stlUserName">
            <!-- usernameEntry add here in code behind -->
        </StackLayout>
    
        <StackLayout x:Name="stlpasswordEntry">
            <!-- passwordEntry add here in code behind -->
        </StackLayout>
    
        <Button Text="Entrar" TextColor="White" Clicked="LoginUser" WidthRequest="110" 
        HorizontalOptions="Center" BackgroundColor="SteelBlue" BorderRadius="20"/>
        <Label x:Name="messageLabel" />
    </StackLayout>
    

    在后面的代码中实例化您的自定义条目

    public Login ()
    {
        InitializeComponent ();
    
        CustomEntryRenderer usernameEntry = new CustomEntryRenderer();
        usernameEntry.CornerRadius="18";
        usernameEntry.IsCurvedCornersEnabled="True";
        usernameEntry.BorderColor="LightBlue"; 
        usernameEntry.HorizontalTextAlignment="Start";
        usernameEntry.FontSize="17";
        usernameEntry.HeightRequest="40";
        usernameEntry.Placeholder="Usuário";
        usernameEntry.PlaceholderColor="LightGray";
        usernameEntry.TextColor="Black";
        usernameEntry.FontAttributes="Bold";
        usernameEntry.WidthRequest="100";
        usernameEntry.ReturnCommand = new Command(() => passwordEntry.Focus());
    
        // Add entry in stacklayout
        stlUserName.Children.Add(usernameEntry);
    
        // do the same for password entry
    }
    

    注意:

    您的条目的一些属性,如CornerRadius,需要正确添加,上面的代码只是说明您需要实例化您的条目,向属性添加值,并将其添加到堆栈布局中。

    【讨论】:

    • 通过 xaml 添加控件应该实例化它。不需要在代码隐藏中手动执行此操作
    • @Jason 你是对的,但这是一种方法,它取决于 Xamarin 的版本。这适用于我所有的自定义控件。
    【解决方案2】:

    在您的 XAML 中,您有 x:Name="usernameEntry" 和一个空格。您必须删除空格。

    【讨论】:

    • 啊哈哈哈是的,就是空间
    猜你喜欢
    • 2020-11-03
    • 2016-09-03
    • 1970-01-01
    • 2021-03-26
    • 1970-01-01
    • 2019-08-31
    • 2021-09-04
    • 1970-01-01
    • 2017-11-07
    相关资源
    最近更新 更多