英文:
Change PasswordBox PlaceHolder Text Foreground color
问题
我有一个PasswordBox控件:
<PasswordBox
MaxLength="12"
PlaceholderText="Password"
Foreground="Black"
Background="#eeeeee"/>
我想要像在常规的TextBox上一样更改PlaceholderForeground
颜色,但是没有这样的属性,在互联网上搜索后,我找不到适合我的解决方案,而且我也不理解,所有的xaml代码都太长,包括50行的样式和资源,用于如此简单的属性更改,我不知道为什么WPF必须如此复杂,没有理由。
有人能提供一个解决方案,可能不需要50行xaml代码,只需简单地更改PasswordBox中占位文本的前景颜色吗?
英文:
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.
答案1
得分: 1
不能在不创建自定义内容的情况下更改占位符颜色。但是有一些绕过方法,而不需要大量的XAML标记。
我想到的最简单的方法是创建一个从PasswordBox
派生的自定义控件。你只需要重写OnRender
方法:
-
调用
base.OnRender
。 -
检查密码框中是否没有文本,并且没有焦点。
-
创建一个
FormattedText
对象,可以像这样:
var placeholder = new FormattedText(
PlaceholderText,
CultureInfo.CurrentCulture,
FlowDirection.LeftToRight,
new Typeface(FontFamily, FontStyle, FontWeight, FontStretch),
FontSize,
new SolidColorBrush(Color.Blue), // 或者任何你想要的颜色
VisualTreeHelper.GetDpi(this).PixelsPerDip);
- 在内容的左上角绘制它:
drawingContext.DrawText(placeholder, new Point(Padding.Left, Padding.Top));
如果你不想要任何额外的代码,我知道的唯一方法是使用第三方库,例如MahApps.Metro。
你也可以为内置的PasswordBox
创建自定义行为,尽管这并不比自定义控件简单。
英文:
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
:
-
Call
base.OnRender
-
Check that there's no text in the password box, and it isn't focused
-
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);
- 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论