Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Picker Title color is unchangeable

using xamarin forms (pcl)

creating Picker

<Picker x:Name="Branches" 
  TextColor="White" Title="Click to choose Branch"
  Grid.Row="3" Grid.Column="1"
  SelectedIndex="{Binding Branches}">
    <Picker.Items>
        <x:String>Id</x:String>
        <x:String>Name</x:String>
    </Picker.Items>
</Picker>

Why is the TextColor of the Title black even tough I explicitly set it to white in XAML?

like image 531
Ahmed Sayed Avatar asked Dec 04 '22 23:12

Ahmed Sayed


1 Answers

Update: Xamarin.Forms v3.6

Xamarin.Forms v3.6 introduces Picker.TitleColor.

It is now possible to set the Picker's TitleColor directly without needing a workaround.

XAML

TitleColor="Red"

<Picker x:Name="Branches" 
  Title="Click to choose Branch"
  TitleColor="Red"
  TextColor="White" 
  Grid.Row="3" 
  Grid.Column="1"
  SelectedIndex="{Binding Branches}">
    <Picker.Items>
        <x:String>Id</x:String>
        <x:String>Name</x:String>
    </Picker.Items>
</Picker>

Code

myPicker.TitleColor = Color.Red

var myPicker = new Picker
{
    TitleColor = Color.Red
};

Explanation

Xamarin.Forms does not allow you to set the color of Picker.Title.

Work Around

Add the title text as the first item in Picker.Items.

Then, set the initial Picker.SelectedIndex to 0. This will show the first item in Picker.Items(aka our title) on the screen by default when the page loads.

Then, add an event handler to Picker.SelectedIndex to prevent the user from selecting the title. It will check to see if the user selected the first item in Picker.Items (aka our Title), and, if true automatically change Picker.SelectedIndex to 1.

using System;

using Xamarin.Forms;

namespace PickerTitleColor
{
    public class App : Application
    {
        public App()
        {
            var picker = new Picker();
            picker.Items.Add("Select an item");
            picker.Items.Add("Item1");
            picker.Items.Add("Item2");
            picker.Items.Add("Item3");
            picker.TextColor = Color.Red;
            picker.SelectedIndex = 0;

            picker.SelectedIndexChanged += (sender, e) => 
            {
                if (picker.SelectedIndex == 0)
                    picker.SelectedIndex = 1;
            };

            var content = new ContentPage
            {
                Title = "Custom Picker Title Color",
                Content = picker
            };

            MainPage = new NavigationPage(content);
        }
    }
}

enter image description here

like image 93
Brandon Minnick Avatar answered Dec 18 '22 02:12

Brandon Minnick