Picker标题颜色不可更改

时间:2017-01-30 14:09:18

标签: c# xaml xamarin xamarin.forms

使用xamarin表格(pcl)

创建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>

为什么TextColor黑色的Title甚至很难我在XAML中明确地将其设置为白色?

1 个答案:

答案 0 :(得分:14)

更新:Xamarin.Forms v3.6

Xamarin.Forms v3.6 introduces Picker.TitleColor

现在可以直接设置Picker TitleColor而无需解决方法。

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>

代码

myPicker.TitleColor = Color.Red

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

解释

Xamarin.Forms不允许您设置Picker.Title的颜色。

解决方法

将标题文字添加为Picker.Items中的第一项。

然后,将初始Picker.SelectedIndex设置为0.这将在页面加载时默认显示屏幕上Picker.Items(也就是我们的标题)中的第一项。

然后,向Picker.SelectedIndex添加一个事件处理程序,以防止用户选择标题。它将检查用户是否选择Picker.Items中的第一项(也就是我们的标题),如果true自动将Picker.SelectedIndex更改为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