Irkl1_
Irkl1_

Reputation: 71

Change PasswordBox PlaceHolder Text Foreground color

I have a PasswordBox

<PasswordBox 
    MaxLength="12" 
    PlaceholderText="Password" 
    Foreground="Black" 
    Background="#eeeeee"/>

And I want to change the PlaceholderForeground color like I would on a regular TextBox but there is no property like that and after searching through the internet I found no solution that A worked for me B I understood, all the xaml code was too lengthy with style and resources of 50 lines all for such a simple property change I don't know why WPF has to be so overly complicated for no reason

Can anybody sugguest a solution that is possibly not 50 lines of xaml code that simply changes the foreground color of the placeholder text in the PasswordBox.

Upvotes: 0

Views: 338

Answers (1)

SNBS
SNBS

Reputation: 849

You can't change the placeholder color without creating something custom. But there are workarounds without huge snippets of XAML markup.

The easiest way that came to my mind is creating a custom control that derives from PasswordBox. You'll only have to override OnRender:

  1. Call base.OnRender

  2. Check that there's no text in the password box, and it isn't focused

  3. Create a FormattedText object, maybe like this:

var placeholder = new FormattedText(
  PlaceholderText,
  CultureInfo.CurrentCulture,
  FlowDirection.LeftToRight,
  new Typeface(FontFamily, FontStyle, FontWeight, FontStretch),
  FontSize,
  new SolidColorBrush(Color.Blue),  // Or whatever you want
  VisualTreeHelper.GetDpi(this).PixelsPerDip);
  1. Draw it at the top-left corner of the content:
drawingContext.DrawText(placeholder, new Point(Padding.Left, Padding.Top));

If you don't want any extra code, the only way I know is using third-party libraries, e.g. MahApps.Metro.

You can also create a custom behavior for the built-in PasswordBox, though it's not much simpler than a custom control.

Upvotes: 1

Related Questions