Xamarin.Forms: Placeholder text color password box Windows Phone

When using the Entry control in Xamarin.Forms with IsPassword set to true the text color property will not affect placeholder text on Windows Phone. To solve this you need to create a custom renderer for entry in your Windows Phone project.

The native control will be a Grid that contains a PasswordBox (PhoneTextBox if IsPassword is false). The easiest way to find the PasswordBox is to loop through all controls in the Grid and set Foreground color to the text color specified on the Xamarin.Forms control.

[assembly: ExportRenderer(typeof(Entry), typeof(ImprovedEntryRenderer))]
namespace MyApp.WinPhone.Renderers
{
      public class ImprovedEntryViewRenderer : EntryRenderer
      {
            protected override void OnElementPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
            {
                 base.OnElementPropertyChanged(sender, e);
 
                 if(e.PropertyName == "Renderer" || e.PropertyName == "TextColor")
                 {
                      foreach(var ctrl in Control)
                      {
                           var control = (System.Windows.Controls.Control)ctrl;
                           control.Foreground = new SolidColorBrush(System.Windows.Media.Color.FromArgb(byte.Parse(TextColor.A), byte.Parse(TextColor.R), byte.Parse(TextColor.G), byte.Parse(TextColor.B)));
                      }
                 }
            }
      }
}

You have to run the code both if e.PropertyName is “Renderer” and if it’s “TextColor”. That’s because first time the control is rendered it will use “Renderer” as property name, if text color then is changes it will be used as property name.

You have to set the foreground in OnElementPropertyChanged, if you set it in OnElementChanged it will be changed by the base class. If you set it in OnElementPropertyChanged after you have called the base method it will be the last that is running in the renderer.

Leave a Reply

Your email address will not be published. Required fields are marked *