Filigrane / texte de conseil / espace réservé TextBox

Comment puis-je insérer du texte dans une zone de texte qui est automatiquement supprimée lorsque l’utilisateur saisit quelque chose? (Dans WPF)

Ceci est un exemple qui montre comment créer une zone de texte de filigrane dans WPF:

                                

TextInputToVisibilityConverter est défini comme suit:

 using System; using System.Windows.Data; using System.Windows; namespace WaterMarkTextBoxDemo { public class TextInputToVisibilityConverter : IMultiValueConverter { public object Convert( object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture ) { // Always test MultiValueConverter inputs for non-null // (to avoid crash bugs for views in the designer) if (values[0] is bool && values[1] is bool) { bool hasText = !(bool)values[0]; bool hasFocus = (bool)values[1]; if (hasFocus || hasText) return Visibility.Collapsed; } return Visibility.Visible; } public object[] ConvertBack( object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture ) { throw new NotImplementedException(); } } } 

Note: Ce n’est pas mon code. Je l’ai trouvé ici , mais je pense que c’est la meilleure approche.

Vous pouvez créer un filigrane pouvant être ajouté à une zone de TextBox avec une propriété jointe. Voici la source de la propriété attachée:

 using System; using System.Collections.Generic; using System.ComponentModel; using System.Windows; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Documents; ///  /// Class that provides the Watermark attached property ///  public static class WatermarkService { ///  /// Watermark Attached Dependency Property ///  public static readonly DependencyProperty WatermarkProperty = DependencyProperty.RegisterAttached( "Watermark", typeof(object), typeof(WatermarkService), new FrameworkPropertyMetadata((object)null, new PropertyChangedCallback(OnWatermarkChanged))); #region Private Fields ///  /// Dictionary of ItemsControls ///  private static readonly Dictionary itemsControls = new Dictionary(); #endregion ///  /// Gets the Watermark property. This dependency property indicates the watermark for the control. ///  ///  to get the property from /// The value of the Watermark property public static object GetWatermark(DependencyObject d) { return (object)d.GetValue(WatermarkProperty); } ///  /// Sets the Watermark property. This dependency property indicates the watermark for the control. ///  ///  to set the property on /// value of the property public static void SetWatermark(DependencyObject d, object value) { d.SetValue(WatermarkProperty, value); } ///  /// Handles changes to the Watermark property. ///  ///  that fired the event /// A  that contains the event data. private static void OnWatermarkChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { Control control = (Control)d; control.Loaded += Control_Loaded; if (d is ComboBox) { control.GotKeyboardFocus += Control_GotKeyboardFocus; control.LostKeyboardFocus += Control_Loaded; } else if (d is TextBox) { control.GotKeyboardFocus += Control_GotKeyboardFocus; control.LostKeyboardFocus += Control_Loaded; ((TextBox)control).TextChanged += Control_GotKeyboardFocus; } if (d is ItemsControl && !(d is ComboBox)) { ItemsControl i = (ItemsControl)d; // for Items property i.ItemContainerGenerator.ItemsChanged += ItemsChanged; itemsControls.Add(i.ItemContainerGenerator, i); // for ItemsSource property DependencyPropertyDescriptor prop = DependencyPropertyDescriptor.FromProperty(ItemsControl.ItemsSourceProperty, i.GetType()); prop.AddValueChanged(i, ItemsSourceChanged); } } #region Event Handlers ///  /// Handle the GotFocus event on the control ///  /// The source of the event. /// A  that contains the event data. private static void Control_GotKeyboardFocus(object sender, RoutedEventArgs e) { Control c = (Control)sender; if (ShouldShowWatermark(c)) { ShowWatermark(c); } else { RemoveWatermark(c); } } ///  /// Handle the Loaded and LostFocus event on the control ///  /// The source of the event. /// A  that contains the event data. private static void Control_Loaded(object sender, RoutedEventArgs e) { Control control = (Control)sender; if (ShouldShowWatermark(control)) { ShowWatermark(control); } } ///  /// Event handler for the items source changed event ///  /// The source of the event. /// A  that contains the event data. private static void ItemsSourceChanged(object sender, EventArgs e) { ItemsControl c = (ItemsControl)sender; if (c.ItemsSource != null) { if (ShouldShowWatermark(c)) { ShowWatermark(c); } else { RemoveWatermark(c); } } else { ShowWatermark(c); } } ///  /// Event handler for the items changed event ///  /// The source of the event. /// A  that contains the event data. private static void ItemsChanged(object sender, ItemsChangedEventArgs e) { ItemsControl control; if (itemsControls.TryGetValue(sender, out control)) { if (ShouldShowWatermark(control)) { ShowWatermark(control); } else { RemoveWatermark(control); } } } #endregion #region Helper Methods ///  /// Remove the watermark from the specified element ///  /// Element to remove the watermark from private static void RemoveWatermark(UIElement control) { AdornerLayer layer = AdornerLayer.GetAdornerLayer(control); // layer could be null if control is no longer in the visual tree if (layer != null) { Adorner[] adorners = layer.GetAdorners(control); if (adorners == null) { return; } foreach (Adorner adorner in adorners) { if (adorner is WatermarkAdorner) { adorner.Visibility = Visibility.Hidden; layer.Remove(adorner); } } } } ///  /// Show the watermark on the specified control ///  /// Control to show the watermark on private static void ShowWatermark(Control control) { AdornerLayer layer = AdornerLayer.GetAdornerLayer(control); // layer could be null if control is no longer in the visual tree if (layer != null) { layer.Add(new WatermarkAdorner(control, GetWatermark(control))); } } ///  /// Indicates whether or not the watermark should be shown on the specified control ///  ///  to test /// true if the watermark should be shown; false otherwise private static bool ShouldShowWatermark(Control c) { if (c is ComboBox) { return (c as ComboBox).Text == ssortingng.Empty; } else if (c is TextBoxBase) { return (c as TextBox).Text == ssortingng.Empty; } else if (c is ItemsControl) { return (c as ItemsControl).Items.Count == 0; } else { return false; } } #endregion } 

La propriété attachée utilise une classe appelée WatermarkAdorner , voici cette source:

 using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Media; ///  /// Adorner for the watermark ///  internal class WatermarkAdorner : Adorner { #region Private Fields ///  ///  that holds the watermark ///  private readonly ContentPresenter contentPresenter; #endregion #region Constructor ///  /// Initializes a new instance of the  class ///  ///  to be adorned /// The watermark public WatermarkAdorner(UIElement adornedElement, object watermark) : base(adornedElement) { this.IsHitTestVisible = false; this.contentPresenter = new ContentPresenter(); this.contentPresenter.Content = watermark; this.contentPresenter.Opacity = 0.5; this.contentPresenter.Margin = new Thickness(Control.Margin.Left + Control.Padding.Left, Control.Margin.Top + Control.Padding.Top, 0, 0); if (this.Control is ItemsControl && !(this.Control is ComboBox)) { this.contentPresenter.VerticalAlignment = VerticalAlignment.Center; this.contentPresenter.HorizontalAlignment = HorizontalAlignment.Center; } // Hide the control adorner when the adorned element is hidden Binding binding = new Binding("IsVisible"); binding.Source = adornedElement; binding.Converter = new BooleanToVisibilityConverter(); this.SetBinding(VisibilityProperty, binding); } #endregion #region Protected Properties ///  /// Gets the number of children for the . ///  protected override int VisualChildrenCount { get { return 1; } } #endregion #region Private Properties ///  /// Gets the control that is being adorned ///  private Control Control { get { return (Control)this.AdornedElement; } } #endregion #region Protected Overrides ///  /// Returns a specified child  for the parent . ///  /// A 32-bit signed integer that represents the index value of the child . The value of index must be between 0 and  - 1. /// The child . protected override Visual GetVisualChild(int index) { return this.contentPresenter; } ///  /// Implements any custom measuring behavior for the adorner. ///  /// A size to constrain the adorner to. /// A  object representing the amount of layout space needed by the adorner. protected override Size MeasureOverride(Size constraint) { // Here's the secret to getting the adorner to cover the whole control this.contentPresenter.Measure(Control.RenderSize); return Control.RenderSize; } ///  /// When overridden in a derived class, positions child elements and determines a size for a  derived class. ///  /// The final area within the parent that this element should use to arrange itself and its children. /// The actual size used. protected override Size ArrangeOverride(Size finalSize) { this.contentPresenter.Arrange(new Rect(finalSize)); return finalSize; } #endregion } 

Maintenant, vous pouvez mettre un filigrane sur une zone de texte comme ceci:

    Type here to search text    

Le filigrane peut être tout ce que vous voulez (texte, images …). En plus de travailler pour TextBoxes, ce filigrane fonctionne également pour ComboBoxes et ItemControls.

Ce code a été adapté de cet article de blog .

Juste en utilisant XAML, pas d’extensions, pas de convertisseurs:

         

Je ne peux pas croire que personne n’a publié l’évidente WPF Toolkit – WatermarkTextBox de Xceed. Cela fonctionne assez bien et est open source au cas où vous souhaitez personnaliser.

Il y a un article sur CodeProject sur la façon de le faire dans “3 lignes de XAML”.

     

Ok, eh bien ce ne sera peut-être pas 3 lignes de format XAML, mais c’est assez simple.

Une chose à noter est qu’elle utilise une méthode d’extension non standard sur la propriété Text, appelée “IsEmpty”. Vous devez le mettre en œuvre vous-même, mais l’article ne semble pas le mentionner.

J’ai vu la solution de John Myczek et ses commentaires sur la compatibilité avec ComboBox et PasswordBox . J’ai donc amélioré la solution de John Myczek et la voici:

 using System; using System.Collections.Generic; using System.ComponentModel; using System.Windows; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Documents; ///  /// Class that provides the Watermark attached property ///  public static class WatermarkService { ///  /// Watermark Attached Dependency Property ///  public static readonly DependencyProperty WatermarkProperty = DependencyProperty.RegisterAttached( "Watermark", typeof(object), typeof(WatermarkService), new FrameworkPropertyMetadata((object)null, new PropertyChangedCallback(OnWatermarkChanged))); #region Private Fields ///  /// Dictionary of ItemsControls ///  private static readonly Dictionary itemsControls = new Dictionary(); #endregion ///  /// Gets the Watermark property. This dependency property indicates the watermark for the control. ///  ///  to get the property from /// The value of the Watermark property public static object GetWatermark(DependencyObject d) { return (object)d.GetValue(WatermarkProperty); } ///  /// Sets the Watermark property. This dependency property indicates the watermark for the control. ///  ///  to set the property on /// value of the property public static void SetWatermark(DependencyObject d, object value) { d.SetValue(WatermarkProperty, value); } ///  /// Handles changes to the Watermark property. ///  ///  that fired the event /// A  that contains the event data. private static void OnWatermarkChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { Control control = (Control)d; control.Loaded += Control_Loaded; if (d is TextBox || d is PasswordBox) { control.GotKeyboardFocus += Control_GotKeyboardFocus; control.LostKeyboardFocus += Control_Loaded; } else if (d is ComboBox) { control.GotKeyboardFocus += Control_GotKeyboardFocus; control.LostKeyboardFocus += Control_Loaded; (d as ComboBox).SelectionChanged += new SelectionChangedEventHandler(SelectionChanged); } else if (d is ItemsControl) { ItemsControl i = (ItemsControl)d; // for Items property i.ItemContainerGenerator.ItemsChanged += ItemsChanged; itemsControls.Add(i.ItemContainerGenerator, i); // for ItemsSource property DependencyPropertyDescriptor prop = DependencyPropertyDescriptor.FromProperty(ItemsControl.ItemsSourceProperty, i.GetType()); prop.AddValueChanged(i, ItemsSourceChanged); } } ///  /// Event handler for the selection changed event ///  /// The source of the event. /// A  that contains the event data. private static void SelectionChanged(object sender, SelectionChangedEventArgs e) { Control control = (Control)sender; if (ShouldShowWatermark(control)) { ShowWatermark(control); } else { RemoveWatermark(control); } } #region Event Handlers ///  /// Handle the GotFocus event on the control ///  /// The source of the event. /// A  that contains the event data. private static void Control_GotKeyboardFocus(object sender, RoutedEventArgs e) { Control c = (Control)sender; if (ShouldShowWatermark(c)) { RemoveWatermark(c); } } ///  /// Handle the Loaded and LostFocus event on the control ///  /// The source of the event. /// A  that contains the event data. private static void Control_Loaded(object sender, RoutedEventArgs e) { Control control = (Control)sender; if (ShouldShowWatermark(control)) { ShowWatermark(control); } } ///  /// Event handler for the items source changed event ///  /// The source of the event. /// A  that contains the event data. private static void ItemsSourceChanged(object sender, EventArgs e) { ItemsControl c = (ItemsControl)sender; if (c.ItemsSource != null) { if (ShouldShowWatermark(c)) { ShowWatermark(c); } else { RemoveWatermark(c); } } else { ShowWatermark(c); } } ///  /// Event handler for the items changed event ///  /// The source of the event. /// A  that contains the event data. private static void ItemsChanged(object sender, ItemsChangedEventArgs e) { ItemsControl control; if (itemsControls.TryGetValue(sender, out control)) { if (ShouldShowWatermark(control)) { ShowWatermark(control); } else { RemoveWatermark(control); } } } #endregion #region Helper Methods ///  /// Remove the watermark from the specified element ///  /// Element to remove the watermark from private static void RemoveWatermark(UIElement control) { AdornerLayer layer = AdornerLayer.GetAdornerLayer(control); // layer could be null if control is no longer in the visual tree if (layer != null) { Adorner[] adorners = layer.GetAdorners(control); if (adorners == null) { return; } foreach (Adorner adorner in adorners) { if (adorner is WatermarkAdorner) { adorner.Visibility = Visibility.Hidden; layer.Remove(adorner); } } } } ///  /// Show the watermark on the specified control ///  /// Control to show the watermark on private static void ShowWatermark(Control control) { AdornerLayer layer = AdornerLayer.GetAdornerLayer(control); // layer could be null if control is no longer in the visual tree if (layer != null) { layer.Add(new WatermarkAdorner(control, GetWatermark(control))); } } ///  /// Indicates whether or not the watermark should be shown on the specified control ///  ///  to test /// true if the watermark should be shown; false otherwise private static bool ShouldShowWatermark(Control c) { if (c is ComboBox) { return (c as ComboBox).SelectedItem == null; //return (c as ComboBox).Text == ssortingng.Empty; } else if (c is TextBoxBase) { return (c as TextBox).Text == ssortingng.Empty; } else if (c is PasswordBox) { return (c as PasswordBox).Password == ssortingng.Empty; } else if (c is ItemsControl) { return (c as ItemsControl).Items.Count == 0; } else { return false; } } #endregion } 

Désormais, une ComboBox Editable peut également être Editable et PasswordBox peut également append un filigrane. N’oubliez pas d’utiliser le commentaire de JoanComasFdz ci-dessus pour résoudre le problème de marge.

Et bien sûr, tout le mérite revient à John Myczek.

J’ai créé une implémentation de code Siple uniquement qui fonctionne bien pour WPF et Silverlight également:

 using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Media; public class TextBoxWatermarked : TextBox { #region [ Dependency Properties ] public static DependencyProperty WatermarkProperty = DependencyProperty.Register("Watermark", typeof(ssortingng), typeof(TextBoxWatermarked), new PropertyMetadata(new PropertyChangedCallback(OnWatermarkChanged))); #endregion #region [ Fields ] private bool _isWatermarked; private Binding _textBinding; #endregion #region [ Properties ] protected new Brush Foreground { get { return base.Foreground; } set { base.Foreground = value; } } public ssortingng Watermark { get { return (ssortingng)GetValue(WatermarkProperty); } set { SetValue(WatermarkProperty, value); } } #endregion #region [ .ctor ] public TextBoxWatermarked() { Loaded += (s, ea) => ShowWatermark(); } #endregion #region [ Event Handlers ] protected override void OnGotFocus(RoutedEventArgs e) { base.OnGotFocus(e); HideWatermark(); } protected override void OnLostFocus(RoutedEventArgs e) { base.OnLostFocus(e); ShowWatermark(); } private static void OnWatermarkChanged(DependencyObject sender, DependencyPropertyChangedEventArgs ea) { var tbw = sender as TextBoxWatermarked; if (tbw == null) return; tbw.ShowWatermark(); } #endregion #region [ Methods ] private void ShowWatermark() { if (ssortingng.IsNullOrEmpty(base.Text)) { _isWatermarked = true; base.Foreground = new SolidColorBrush(Colors.Gray); var bindingExpression = GetBindingExpression(TextProperty); _textBinding = bindingExpression == null ? null : bindingExpression.ParentBinding; if (bindingExpression != null) bindingExpression.UpdateSource(); SetBinding(TextProperty, new Binding()); base.Text = Watermark; } } private void HideWatermark() { if (_isWatermarked) { _isWatermarked = false; ClearValue(ForegroundProperty); base.Text = ""; SetBinding(TextProperty, _textBinding ?? new Binding()); } } #endregion } 

Usage:

  

Solution simple utilisant le style:

      

Excellente solution:

https://code.msdn.microsoft.com/windowsdesktop/In-place-hit-messages-for-18db3a6c

Cette bibliothèque a un filigrane.

Paquet Nuget

Exemple d’utilisation:

  

J’ai rencontré quelques difficultés lors de l’utilisation du code de @ john-myczek avec une zone de texte liée. Comme le TextBox ne déclenche pas un événement de focus lorsqu’il est mis à jour, le filigrane rest visible sous le nouveau texte. Pour résoudre ce problème, j’ai simplement ajouté un autre gestionnaire d’événement:

 if (d is ComboBox || d is TextBox) { control.GotKeyboardFocus += Control_GotKeyboardFocus; control.LostKeyboardFocus += Control_Loaded; if (d is TextBox) (d as TextBox).TextChanged += Control_TextChanged; } private static void Control_TextChanged(object sender, RoutedEventArgs e) { var tb = (TextBox)sender; if (ShouldShowWatermark(tb)) { ShowWatermark(tb); } else { RemoveWatermark(tb); } } 

@Veton – J’aime beaucoup la simplicité de votre solution, mais ma réputation n’est pas suffisante pour vous casser la gueule.

@Tim Murphy – Cette erreur était une solution simple: mise à jour du code, y compris d’autres petites modifications (test WPF uniquement):

 using System; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Media; public class TextBoxWatermarked : TextBox { public ssortingng Watermark { get { return (ssortingng)GetValue(WaterMarkProperty); } set { SetValue(WaterMarkProperty, value); } } public static readonly DependencyProperty WaterMarkProperty = DependencyProperty.Register("Watermark", typeof(ssortingng), typeof(TextBoxWatermarked), new PropertyMetadata(new PropertyChangedCallback(OnWatermarkChanged))); private bool _isWatermarked = false; private Binding _textBinding = null; public TextBoxWatermarked() { Loaded += (s, ea) => ShowWatermark(); } protected override void OnGotFocus(RoutedEventArgs e) { base.OnGotFocus(e); HideWatermark(); } protected override void OnLostFocus(RoutedEventArgs e) { base.OnLostFocus(e); ShowWatermark(); } private static void OnWatermarkChanged(DependencyObject sender, DependencyPropertyChangedEventArgs ea) { var tbw = sender as TextBoxWatermarked; if (tbw == null || !tbw.IsLoaded) return; //needed to check IsLoaded so that we didn't dive into the ShowWatermark() routine before initial Bindings had been made tbw.ShowWatermark(); } private void ShowWatermark() { if (Ssortingng.IsNullOrEmpty(Text) && !Ssortingng.IsNullOrEmpty(Watermark)) { _isWatermarked = true; //save the existing binding so it can be restored _textBinding = BindingOperations.GetBinding(this, TextProperty); //blank out the existing binding so we can throw in our Watermark BindingOperations.ClearBinding(this, TextProperty); //set the signature watermark gray Foreground = new SolidColorBrush(Colors.Gray); //display our watermark text Text = Watermark; } } private void HideWatermark() { if (_isWatermarked) { _isWatermarked = false; ClearValue(ForegroundProperty); Text = ""; if (_textBinding != null) SetBinding(TextProperty, _textBinding); } } } 

David Owens a un exemple plus compliqué d’une “boîte de recherche” complète ici .

Si vous écrivez des applications UWP sur Windows 10, cela est beaucoup plus facile.

Plus d’infos: https://msdn.microsoft.com/en-us/library/windows/apps/windows.ui.xaml.controls.textbox.placeholdertext.aspx

      

This can help check it with your code.When applied to password box,it will show Password,which will disappear when usertypes.

you can use GetFocus() and LostFocus() events to do this

here is the example:

  private void txtData1_GetFocus(object sender, RoutedEventArgs e) { if (txtData1.Text == "TextBox1abc") { txtData1.Text = ssortingng.Empty; } } private void txtData1_LostFocus(object sender, RoutedEventArgs e) { if (txtData1.Text == ssortingng.Empty) { txtData1.Text = "TextBox1abc"; } } 

Well here is mine: not necessarily the best, but as it is simple it is easy to edit to your taste.

               

The converter, as it is written now it is not necessary that it is a MultiConverter, but in this wasy it can be extended easily

 using System; using System.Globalization; using System.Windows; using System.Windows.Data; namespace WPFControls { class ShadowConverter:IMultiValueConverter { #region Implementation of IMultiValueConverter public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) { var text = (ssortingng) values[0]; return text == ssortingng.Empty ? Visibility.Visible : Visibility.Collapsed; } public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) { return new object[0]; } #endregion } } 

and finally the code behind:

 using System.Windows; using System.Windows.Controls; namespace WPFControls { ///  /// Interaction logic for ShadowedTextBox.xaml ///  public partial class ShadowedTextBox : UserControl { public event TextChangedEventHandler TextChanged; public ShadowedTextBox() { InitializeComponent(); } public static readonly DependencyProperty WatermarkProperty = DependencyProperty.Register("Watermark", typeof (ssortingng), typeof (ShadowedTextBox), new UIPropertyMetadata(ssortingng.Empty)); public static readonly DependencyProperty TextProperty = DependencyProperty.Register("Text", typeof (ssortingng), typeof (ShadowedTextBox), new UIPropertyMetadata(ssortingng.Empty)); public static readonly DependencyProperty TextChangedProperty = DependencyProperty.Register("TextChanged", typeof (TextChangedEventHandler), typeof (ShadowedTextBox), new UIPropertyMetadata(null)); public ssortingng Watermark { get { return (ssortingng)GetValue(WatermarkProperty); } set { SetValue(WatermarkProperty, value); } } public ssortingng Text { get { return (ssortingng) GetValue(TextProperty); } set{SetValue(TextProperty,value);} } private void textBox_TextChanged(object sender, TextChangedEventArgs e) { if (TextChanged != null) TextChanged(this, e); } public void Clear() { textBox.Clear(); } } } 
   

MahApps.Metro for WPF has a built-in watermark control, if you’d rather not roll your own. It’s fairly straightforward to use.

    I'm a watermark!   

Set up the text box with placeholder text in a soft color…

 public MainWindow ( ) { InitializeComponent ( ); txtInput.Text = "Type something here..."; txtInput.Foreground = Brushes.DimGray; } 

When the text box gets the focus, clear it and change the text color

 private void txtInput_GotFocus ( object sender, EventArgs e ) { MessageBox.Show ( "got focus" ); txtInput.Text = ""; txtInput.Foreground = Brushes.Red; } 

hi i put this task into a behavior. so you just have to add somthing like this to your textbox

    

you can find my blog post here

My solution is quite simple.

In my login window. the xaml is like this.

            

the code is like this.

 private void userNameWatermarked_GotFocus(object sender, RoutedEventArgs e) { userNameWatermarked.Visibility = System.Windows.Visibility.Collapsed; userName.Visibility = System.Windows.Visibility.Visible; userName.Focus(); } private void userName_LostFocus(object sender, RoutedEventArgs e) { if (ssortingng.IsNullOrEmpty(this.userName.Text)) { userName.Visibility = System.Windows.Visibility.Collapsed; userNameWatermarked.Visibility = System.Windows.Visibility.Visible; } } private void passwordWatermarked_GotFocus(object sender, RoutedEventArgs e) { passwordWatermarked.Visibility = System.Windows.Visibility.Collapsed; password.Visibility = System.Windows.Visibility.Visible; password.Focus(); } private void password_LostFocus(object sender, RoutedEventArgs e) { if (ssortingng.IsNullOrEmpty(this.password.Password)) { password.Visibility = System.Windows.Visibility.Collapsed; passwordWatermarked.Visibility = System.Windows.Visibility.Visible; } } 

Just decide to hide or show the watermark textbox is enough. Though not beautiful,but work well.

This technique uses the Background property to show / hide placeholder textbox.
Placeholder is shown event when Textbox has the focus

Comment ça marche:

  • When empty, TextBox background set to Transparent to show PlaceHolder text.
  • When not empty background set to White to cover up PlaceHolder text.

Here is basic example. For my own purposes I turned this into a UserControl.

                 

Here is the ValueConverter to detect non-empty ssortingngs in the DataTrigger.

 public class NotEmptyConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { var s = value as ssortingng; return ssortingng.IsNullOrEmpty(s); } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { return null; } } 

You can keep a seperate value for the entered text and you can set it along with the “Text” field of the text box in the “GotFocus” and “LostFocus” events. When you get the focus, you’ll want to clear the text box if there is no value. And when you loss the focus, you’ll want to set the get the “Text” value from the text box and then reset the “Text” value of the text box to the place holder if it is empty.

 private Ssortingng username = ""; private void usernameTextBox_GotFocus(object sender, RoutedEventArgs e) { if (Ssortingng.IsNullOrEmpty(username)) { usernameTextBox.Text = ""; } } private void usernameTextBox_LostFocus(object sender, RoutedEventArgs e) { username = usernameTextBox.Text; if (Ssortingng.IsNullOrEmpty(usernameTextBox.Text)) { usernameTextBox.Text = "Username"; } } 

Then you just have to make sure that the “Text” value of the text box is initialized to the place holder text.

  

You can further extract this into a class that extends the “TextBox” class and then reuse it through out your project.

 namespace UI { public class PlaceholderTextBox : TextBox { public Ssortingng Value { get; set; } public Ssortingng PlaceholderText { get; set; } public Brush PlaceholderBrush { get; set; } private Brush ValuedBrush { get; set; } public PlaceholderTextBox() : base() {} protected override void OnInitialized(EventArgs e) { base.OnInitialized(e); ValuedBrush = this.Foreground; if (Ssortingng.IsNullOrEmpty(this.Text)) { this.Text = PlaceholderText; this.Foreground = PlaceholderBrush; } } protected override void OnGotFocus(System.Windows.RoutedEventArgs e) { this.Foreground = ValuedBrush; if (Ssortingng.IsNullOrEmpty(Value)) { this.Text = ""; } base.OnGotFocus(e); } protected override void OnLostFocus(System.Windows.RoutedEventArgs e) { Value = this.Text; if (Ssortingng.IsNullOrEmpty(this.Text)) { this.Text = PlaceholderText; this.Foreground = PlaceholderBrush; } base.OnLostFocus(e); } } } 

And then this can be added in the directly in the xaml.

      

If rather than having the watermark’s visibility depend on the control’s focus state, you want it to depend on whether the user has entered any text, you can update John Myczek’s answer (from OnWatermarkChanged down) to

 static void OnWatermarkChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var textbox = (TextBox)d; textbox.Loaded += UpdateWatermark; textbox.TextChanged += UpdateWatermark; } static void UpdateWatermark(object sender, RoutedEventArgs e) { var textbox = (TextBox)sender; var layer = AdornerLayer.GetAdornerLayer(textbox); if (layer != null) { if (textbox.Text == ssortingng.Empty) { layer.Add(new WatermarkAdorner(textbox, GetWatermark(textbox))); } else { var adorners = layer.GetAdorners(textbox); if (adorners == null) { return; } foreach (var adorner in adorners) { if (adorner is WatermarkAdorner) { adorner.Visibility = Visibility.Hidden; layer.Remove(adorner); } } } } } 

This makes more sense if your textbox gets focus automatically when displaying the form, or when databinding to the Text property.

Also if your watermark is always just a ssortingng, and you need the style of the watermark to match the style of the textbox, then in the Adorner do:

 contentPresenter = new ContentPresenter { Content = new TextBlock { Text = (ssortingng)watermark, Foreground = Control.Foreground, Background = Control.Background, FontFamily = Control.FontFamily, FontSize = Control.FontSize, ... }, ... } 

Here’s my approach Is great for MVVM where I also check if the Text box has focus, you can also use a regular sortinggger just for the text value as well the point is I just change the background Image when value changes:

      

I decided to solve this via a Behavior. It uses a Hint property to define the text to display (could also be an object, if you prefer) and a Value property to evaluate wether the hint should be visible or not.

The Behavior is declared as follows:

 using System; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Interactivity; using System.Windows.Media; public class HintBehavior : Behavior { public static readonly DependencyProperty HintProperty = DependencyProperty .Register("Hint", typeof (ssortingng), typeof (HintBehavior) //, new FrameworkPropertyMetadata(null, OnHintChanged) ); public ssortingng Hint { get { return (ssortingng) GetValue(HintProperty); } set { SetValue(HintProperty, value); } } public static readonly DependencyProperty ValueProperty = DependencyProperty .Register("Value", typeof (object), typeof (HintBehavior) , new FrameworkPropertyMetadata(null, OnValueChanged)); private static void OnValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var visible = e.NewValue == null; d.SetValue(VisibilityProperty, visible ? Visibility.Visible : Visibility.Collapsed); } public object Value { get { return GetValue(ValueProperty); } set { SetValue(ValueProperty, value); } } public static readonly DependencyProperty VisibilityProperty = DependencyProperty .Register("Visibility", typeof (Visibility), typeof (HintBehavior) , new FrameworkPropertyMetadata(Visibility.Visible //, new PropertyChangedCallback(OnVisibilityChanged) )); public Visibility Visibility { get { return (Visibility) GetValue(VisibilityProperty); } set { SetValue(VisibilityProperty, value); } } public static readonly DependencyProperty ForegroundProperty = DependencyProperty .Register("Foreground", typeof (Brush), typeof (HintBehavior) , new FrameworkPropertyMetadata(new SolidColorBrush(Colors.DarkGray) //, new PropertyChangedCallback(OnForegroundChanged) )); public Brush Foreground { get { return (Brush) GetValue(ForegroundProperty); } set { SetValue(ForegroundProperty, value); } } public static readonly DependencyProperty MarginProperty = DependencyProperty .Register("Margin", typeof (Thickness), typeof (HintBehavior) , new FrameworkPropertyMetadata(new Thickness(4, 5, 0, 0) //, new PropertyChangedCallback(OnMarginChanged) )); public Thickness Margin { get { return (Thickness) GetValue(MarginProperty); } set { SetValue(MarginProperty, value); } } private static ResourceDictionary _hintBehaviorResources; public static ResourceDictionary HintBehaviorResources { get { if (_hintBehaviorResources == null) { var res = new ResourceDictionary { Source = new Uri("/Mayflower.Client.Core;component/Behaviors/HintBehaviorResources.xaml", UriKind.RelativeOrAbsolute) }; _hintBehaviorResources = res; } return _hintBehaviorResources; } } protected override void OnAttached() { base.OnAttached(); var t = (ControlTemplate) HintBehaviorResources["HintBehaviorWrapper"]; AssociatedObject.Template = t; AssociatedObject.Loaded += OnLoaded; } private void OnLoaded(object sender, RoutedEventArgs e) { AssociatedObject.Loaded -= OnLoaded; var label = (Label) AssociatedObject.Template.FindName("PART_HintLabel", AssociatedObject); label.DataContext = this; //label.Content = "Hello..."; label.SetBinding(UIElement.VisibilityProperty, new Binding("Visibility") {Source = this, Mode = BindingMode.OneWay}); label.SetBinding(ContentControl.ContentProperty, new Binding("Hint") {Source = this, Mode = BindingMode.OneWay}); label.SetBinding(Control.ForegroundProperty, new Binding("Foreground") {Source = this, Mode = BindingMode.OneWay}); label.SetBinding(FrameworkElement.MarginProperty, new Binding("Margin") {Source = this, Mode = BindingMode.OneWay}); } } 

It wraps the target with it’s own template, adding to it a label:

         

To use it, just add it as a behavior and bind your values (in my case I add it in a ControlTemplate, hence the binding):

       

I would love feedback if this is considered a clean solution. It does not require static dictionaries and hence has no memory leak.

I found this way to do it in a very fast and easy way

   Please select ...  First Item Second Item third Item  

Maybe it can help to anyone trying to do this

Source: http://www.admindiaries.com/displaying-a-please-select-watermark-type-text-in-a-wpf-combobox/

 namespace PlaceholderForRichTexxBoxInWPF { public MainWindow() { InitializeComponent(); Application.Current.MainWindow.WindowState = WindowState.Maximized;// maximize window on load richTextBox1.GotKeyboardFocus += new KeyboardFocusChangedEventHandler(rtb_GotKeyboardFocus); richTextBox1.LostKeyboardFocus += new KeyboardFocusChangedEventHandler(rtb_LostKeyboardFocus); richTextBox1.AppendText("Place Holder"); richTextBox1.Foreground = Brushes.Gray; } private void rtb_GotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e) { if (sender is RichTextBox) { TextRange textRange = new TextRange(richTextBox1.Document.ContentStart, richTextBox1.Document.ContentEnd); if (textRange.Text.Trim().Equals("Place Holder")) { ((RichTextBox)sender).Foreground = Brushes.Black; richTextBox1.Document.Blocks.Clear(); } } } private void rtb_LostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e) { //Make sure sender is the correct Control. if (sender is RichTextBox) { //If nothing was entered, reset default text. TextRange textRange = new TextRange(richTextBox1.Document.ContentStart, richTextBox1.Document.ContentEnd); if (textRange.Text.Trim().Equals("")) { ((RichTextBox)sender).Foreground = Brushes.Gray; ((RichTextBox)sender).AppendText("Place Holder"); } } } } 
   private void TextBox_Watermark_GotFocus( object sender, RoutedEventArgs e ) { TextBox_Watermark.Visibility = Visibility.Hidden; TextBox_SearchBar.Focus(); } 
  

Add mahapps.metro to your project. Add textbox with the above code to the window.