如何在passwordBox wpf中设置一些默认文本?

可能重复:
WPF中的水印TextBox

我可以知道如何在WPF的密码框中放置一些默认文本吗? 我以MSN messenger为例。 默认情况下,密码字段将在密码框中显示“密码”。 当我单击并在密码框中键入时,“密码”文本将消失,点将替换它。

在此处输入图像描述

在此处输入图像描述

您必须创建自定义控件才能执行此操作。

XAML:

        

C#代码:

 using System.Windows; using System.Windows.Controls; namespace WpfTest { public partial class Window1 : Window { public Window1() { InitializeComponent(); } } public class PasswordBoxMonitor : DependencyObject { public static bool GetIsMonitoring(DependencyObject obj) { return (bool)obj.GetValue(IsMonitoringProperty); } public static void SetIsMonitoring(DependencyObject obj, bool value) { obj.SetValue(IsMonitoringProperty, value); } public static readonly DependencyProperty IsMonitoringProperty = DependencyProperty.RegisterAttached("IsMonitoring", typeof(bool), typeof(PasswordBoxMonitor), new UIPropertyMetadata(false, OnIsMonitoringChanged)); public static int GetPasswordLength(DependencyObject obj) { return (int)obj.GetValue(PasswordLengthProperty); } public static void SetPasswordLength(DependencyObject obj, int value) { obj.SetValue(PasswordLengthProperty, value); } public static readonly DependencyProperty PasswordLengthProperty = DependencyProperty.RegisterAttached("PasswordLength", typeof(int), typeof(PasswordBoxMonitor), new UIPropertyMetadata(0)); private static void OnIsMonitoringChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var pb = d as PasswordBox; if (pb == null) { return; } if ((bool) e.NewValue) { pb.PasswordChanged += PasswordChanged; } else { pb.PasswordChanged -= PasswordChanged; } } static void PasswordChanged(object sender, RoutedEventArgs e) { var pb = sender as PasswordBox; if (pb == null) { return; } SetPasswordLength(pb, pb.Password.Length); } } } 

参考: Watermark TextBox的WPF Watermark PasswordBox