How to change Picker font colour and size in Xamarin forms?

末鹿安然 提交于 2019-12-10 10:57:27

问题


I'm new to Xamarin and I'm currently doing a project in Xamarin Forms PCL.

Is there a way to change the font colour and size of Picker?

  <Picker x:Name="pkr_color" Grid.Row="4" Grid.Column="1" HorizontalOptions="FillAndExpand"
    BackgroundColor="#ededed" Title="Select Color">
      <Picker.Items>
        <x:String>Red</x:String>
        <x:String>Blue</x:String>
        <x:String>Green</x:String>
      </Picker.Items>
    </Picker>

Thanks in advance!


回答1:


You will need to write a custom renderer for each platform.

using System;
using Project.iOS;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;

[assembly: ExportRenderer (typeof (Picker), typeof (CustomPickerRenderer))]
namespace Project.iOS
{
    public class CustomPickerRenderer : PickerRenderer
    {
        protected override void OnElementChanged (ElementChangedEventArgs<Picker> e)
        {
            base.OnElementChanged (e);
            if (Control != null) {
                Control.TextColor = UIKit.UIColor.White;
            }
        }
    }
}

Here is an example for iOS. This would change the color of the text, you will need to do something similar for Android, and just add your font sizing change as well.




回答2:


Font size of a picker can be changed with PCL code.

Create MainPage.xaml file

<Picker x:Name="PickerList" Title="Select Any One" IsVisible="False" SelectedIndexChanged="PickerList_SelectedIndexChanged">
        <Picker.Items>
            <x:String>Option 1</x:String>
            <x:String>Option 2</x:String>
            <x:String>Option 3</x:String>
        </Picker.Items>
    </Picker>
    <Label x:Name="PickerLabel" Text="Tap to Select Picker" FontSize="14" HorizontalOptions="Start">
        <Label.GestureRecognizers>
            <TapGestureRecognizer Tapped="TapGestureRecognizer_Tapped"/>
        </Label.GestureRecognizers>
    </Label>

Create MainPage.xaml.cs file

private void PickerList_SelectedIndexChanged(object sender, EventArgs e)
    {
        PickerLabel.Text = PickerList.Items[PickerList.SelectedIndex];
        // PickerLabel.Text = PickerList.SelectedItem.ToString() ;
    }

    private void TapGestureRecognizer_Tapped(object sender, EventArgs e)
    {
        PickerList.Focus();
    }

this solves the problem for Android and IOS.




回答3:


I Hope Below Code Helpful to Get Your TextColor

**In Xaml**

 <Picker SelectedIndexChanged="OnColorPickerSelected" TextColor="{Binding TextColor}"/>


**In Code Behind**

 private void OnColorPickerSelected(object sender, EventArgs e)
 {
   ((ViewModel)BindingContext).Color= pkr_color.Items[pkr_color.SelectedIndex];

   ChooseColorPickerTextColor(((ViewModel)BindingContext).Color, pkr_color);
 }

**Implement ChooseColorPickerTextColor Method Here**

  private void ChooseColorPickerTextColor(string selectedColor, Picker pickerName)
    {
        Picker colorPickerTextColor = pickerName;

        if (selectedColor == "Red")
        {
            colorPickerTextColor.TextColor = Color.Red;
        }
        else if (selectedColor == "Yellow")
        {
            colorPickerTextColor.TextColor = Color.Yellow;
        }
        else if (selectedColor == "Green")
        {
            colorPickerTextColor.TextColor = Color.Green;
        }
        else if (selectedColor == "Blue")
        {
            colorPickerTextColor.TextColor = Color.Blue;
        }
        else if (selectedColor == "Maroon")
        {
            colorPickerTextColor.TextColor = Color.Maroon;
        }
        else if (selectedColor == "Pink")
        {
            colorPickerTextColor.TextColor = Color.Pink;
        }
        else
        {
            colorPickerTextColor.TextColor = Color.Aqua;
        }
    }

By using "WidthRequest" We can Increase size of the picker




回答4:


For changing typeface, size, underline, text, textcolor, alert dialog button position, button text in Android native numberpicker (xamarin form picker), you can handle it with a custom render like this:

using System;
using System.Collections.Generic;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;
using Android.Graphics.Drawables;
using Android.Graphics;

[assembly: ExportRenderer(typeof(Picker), typeof(MyPickerRenderer))]
namespace Daddy.Droid
{
    public class MyPickerRenderer : Xamarin.Forms.Platform.Android.PickerRenderer
    {
        Typeface fontFace = null;
        private IElementController ElementController => Element as IElementController;
        private AlertDialog _dialog;
        public MyPickerRenderer(Context context) : base(context)
        {
            AutoPackage = false;
        }
        [Obsolete("This constructor is obsolete as of version 2.5. Please use PickerRenderer(Context) instead.")]
        public MyPickerRenderer()
        {
            AutoPackage = false;
        }
        protected override void OnElementChanged(ElementChangedEventArgs<Picker> e)
        {
            base.OnElementChanged(e);

            if (e.NewElement == null || e.OldElement != null || Control == null)
                return;

            fontFace = Typeface.CreateFromAsset(this.Context.Assets, "somefont.ttf");

            GradientDrawable gd = new GradientDrawable();
            gd.SetStroke(0, Android.Graphics.Color.Transparent);
            Control.SetBackground(gd);

            Control.TextSize = 14f;
            Control.SetTypeface(fontFace, TypefaceStyle.Normal);

            Control.Click += Control_Click;
        }
        protected override void Dispose(bool disposing)
        {
            Control.Click -= Control_Click;
            base.Dispose(disposing);
        }

        private void Control_Click(object sender, EventArgs e)
        {
            Picker model = Element;
            NumberPicker picker = new NumberPicker(Context);

            int count = picker.ChildCount;
            for (int i = 0; i < count; i++)
            {
                Android.Views.View v = picker.GetChildAt(i);
                if(v.GetType() == typeof(EditText))
                {
                    Java.Lang.Reflect.Field  field = picker.Class.GetDeclaredField("mSelectorWheelPaint");
                    field.Accessible = true;
                    ((Paint)field.Get(picker)).SetTypeface(fontFace);
                    ((EditText)v).SetTypeface(fontFace, TypefaceStyle.Normal);
                    picker.Invalidate();   
                }
            }

            if (model.Items != null && model.Items.Any())
            {
                picker.MaxValue = model.Items.Count - 1;
                picker.MinValue = 0;
                picker.SetDisplayedValues(model.Items.ToArray());
                picker.WrapSelectorWheel = false;
                picker.DescendantFocusability = DescendantFocusability.BlockDescendants;
                picker.Value = model.SelectedIndex;
                picker.Visibility = ViewStates.Visible;

            }


            var layout = new LinearLayout(Context) { Orientation = Orientation.Vertical };
            layout.Visibility = ViewStates.Visible;
            layout.AddView(picker);


            ElementController.SetValueFromRenderer(VisualElement.IsFocusedProperty, true);

            var builder = new AlertDialog.Builder(Context); 
            builder.SetView(layout);

            builder.SetTitle(model.Title ?? "");

            builder.SetNegativeButton("Cancel", (s, a) =>
            {
                ElementController.SetValueFromRenderer(VisualElement.IsFocusedProperty, false);
                Control?.ClearFocus();
                _dialog = null;
            });

            builder.SetPositiveButton("This One", (s, a) =>
            {
                ElementController.SetValueFromRenderer(Picker.SelectedIndexProperty, picker.Value);
                if (Element != null)
                {
                    if (model.Items.Count > 0 && Element.SelectedIndex >= 0)
                        Control.Text = model.Items[Element.SelectedIndex];
                    ElementController.SetValueFromRenderer(VisualElement.IsFocusedProperty, false);
                    Control?.ClearFocus();
                }
                _dialog = null;
            });

            _dialog = builder.Create();

            _dialog.DismissEvent += (ssender, args) =>
            {
                ElementController?.SetValueFromRenderer(VisualElement.IsFocusedProperty, false);
            };
            _dialog.Show();


            Android.Widget.Button nbutton = _dialog.GetButton((int)Android.Content.DialogButtonType.Positive);
            nbutton.SetTypeface(fontFace, TypefaceStyle.Normal);
            nbutton.SetTextColor(Android.Graphics.Color.ParseColor("#33b5e5"));
            nbutton.TextSize = 16f;
            LinearLayout layOut = (LinearLayout)nbutton.Parent;
            layOut.SetGravity(GravityFlags.CenterHorizontal);
            Android.Views.View v1 = layOut.GetChildAt(1);
            v1.Visibility = ViewStates.Gone;


            int res = Resources.GetIdentifier("alertTitle", "id", "android");
            TextView textView = (TextView)_dialog.FindViewById(res);
            textView.SetTextColor(Android.Graphics.Color.Gray);
            textView.SetTypeface(fontFace, TypefaceStyle.Normal);
            textView.Gravity = GravityFlags.Center;

        }
    }
}



回答5:


Put the Label and Picker in the same Grid cell.Don't set Title of the picker instead the Text of the Label will work as Title.

<Label x:Name="PickerLabel" Text="Picker Title" TextColor="Any Color"></Label>
         <Picker x:Name="Picker" SelectedIndexChanged="Picker_SelectedIndexChanged" TextColor="Any Color" />

Now make the Text of Label Invisible when an Item is selected from Picker.

void Picker_SelectedIndexChanged(object sender, System.EventArgs e)
        {
            PickerLabel.IsVisible = false;
        }



回答6:


an option can be, the use of Scale. For example, in xaml:

<Picker Scale="0.5">
      <Picker.Items>
        <x:String>Red</x:String>
        <x:String>Blue</x:String>
        <x:String>Green</x:String>
      </Picker.Items>
</Picker>


来源:https://stackoverflow.com/questions/39900804/how-to-change-picker-font-colour-and-size-in-xamarin-forms

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!