自定义条目null xamarin

时间:2019-08-29 13:56:14

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

我在“登录”页面上创建了一个自定义条目,但是该条目为空 我刚刚创建了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为空

我必须实例化吗?

2 个答案:

答案 0 :(得分:0)

在添加命令之前,您需要实例化自定义条目。使用自定义条目的正确方法基本上是以下示例:

添加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,上面的代码仅演示了您需要实例化条目,为属性添加值并将其添加到堆栈布局。 / p>

答案 1 :(得分:0)

在XAML中,您的x:Name =“ usernameEntry”带有空格。您必须删除空格。