private static void OnTextFocus(object sender, RoutedEventArgs e) { WatermarkTextBox txtBox = sender as WatermarkTextBox; TextBlock watermarkTextBlock = txtBox.Template.FindName("Watermark", txtBox) as TextBlock; if (txtBox.IsFocused) { txtBox.RaiseEvent(new RoutedEventArgs(TextFocusOnEvent)); } else { txtBox.RaiseEvent(new RoutedEventArgs(TextLostFocusOnEvent)); } if (watermarkTextBlock != null) { if (e.RoutedEvent.Name == "GotFocus") { if (txtBox.Text.Length == 0) { watermarkTextBlock.Visibility = Visibility.Hidden; } } else if (e.RoutedEvent.Name == "LostFocus") { if (txtBox.Text.Length == 0) { watermarkTextBlock.Visibility = Visibility.Visible; } } } }
private static void OnWatermarkChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e) { WatermarkTextBox txtBox = sender as WatermarkTextBox; if (txtBox != null) { txtBox.GotFocus -= OnTextFocus; txtBox.GotFocus += OnTextFocus; txtBox.LostFocus -= OnTextFocus; txtBox.LostFocus += OnTextFocus; txtBox.TextChanged -= OnTextBoxChanged; txtBox.TextChanged += OnTextBoxChanged; return; } PasswordBox pwdBox = sender as PasswordBox; if (pwdBox != null) { pwdBox.PasswordChanged -= OnPasswordChanged; pwdBox.PasswordChanged += OnPasswordChanged; pwdBox.GotFocus -= OnPasswordFocus; pwdBox.GotFocus += OnPasswordFocus; pwdBox.LostFocus -= OnPasswordFocus; pwdBox.LostFocus += OnPasswordFocus; return; } }
private static void OnTextBoxChanged(object sender, RoutedEventArgs e) { try { WatermarkTextBox txtBox = sender as WatermarkTextBox; TextBlock watermarkTextBlock = txtBox.Template.FindName("Watermark", txtBox) as TextBlock; if (watermarkTextBlock != null) { watermarkTextBlock.Visibility = txtBox.Text.Length == 0 ? Visibility.Visible : Visibility.Hidden; } } catch (Exception) { } }