Watermark / hint text / placeholder TextBox

Como posso colocar algum texto em uma checkbox de texto que é removida automaticamente quando o usuário digita algo nele? (No WPF)

Este é um exemplo que demonstra como criar uma checkbox de texto de marca d’água no WPF:

                                

TextInputToVisibilityConverter é definido como:

 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(); } } } 

Nota: Este não é o meu código. Eu encontrei aqui , mas acho que esta é a melhor abordagem.

Você pode criar uma marca d’água que pode ser adicionada a qualquer TextBox com uma propriedade anexada. Aqui está a fonte da propriedade anexada:

 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 == string.Empty; } else if (c is TextBoxBase) { return (c as TextBox).Text == string.Empty; } else if (c is ItemsControl) { return (c as ItemsControl).Items.Count == 0; } else { return false; } } #endregion } 

A Propriedade Anexada usa uma class chamada WatermarkAdorner , aqui está essa fonte:

 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 } 

Agora você pode colocar uma marca d’água em qualquer TextBox assim:

    Type here to search text    

A marca d’água pode ser o que você quiser (texto, imagens …). Além de trabalhar para TextBoxes, essa marca d’água também funciona para ComboBoxes e ItemControls.

Este código foi adaptado desta postagem do blog .

Apenas usando XAML, sem extensões, sem conversores:

          

Eu não posso acreditar que ninguém postou o óbvio Toolkit Extended WPF – WatermarkTextBox da Xceed. Funciona muito bem e é de código aberto, caso você queira personalizar.

Há um artigo no CodeProject sobre como fazer isso em “3 linhas de XAML”.

     

Ok, bem, pode não ser 3 linhas de XAML formatadas, mas é bem simples.

Uma coisa a notar, porém, é que ele usa um método de extensão não padrão na propriedade Text, chamado “IsEmpty”. Você precisa implementar isso sozinho, no entanto, o artigo não parece mencionar isso.

Eu vi a solução de John Myczek e seus comentários sobre Compatibility para ComboBox e PasswordBox , então eu melhorei a solução de John Myczek, e aqui está:

 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 == string.Empty; } else if (c is TextBoxBase) { return (c as TextBox).Text == string.Empty; } else if (c is PasswordBox) { return (c as PasswordBox).Password == string.Empty; } else if (c is ItemsControl) { return (c as ItemsControl).Items.Count == 0; } else { return false; } } #endregion } 

Agora, um ComboBox também pode ser Editable , e o PasswordBox pode adicionar uma marca d’água. Não esqueça de usar o comentário de JoanComasFdz acima para resolver o problema da margem.

E, claro, todo o crédito vai para John Myczek.

Eu criei apenas a implementação de código de siple que funciona bem para o WPF e o Silverlight também:

 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(string), 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 string Watermark { get { return (string)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 (string.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 } 

Uso:

  

Solução simples usando o estilo:

        

Ótima solução:

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

Esta biblioteca tem uma marca d’água.

Pacote Nuget

Uso da amostra:

  

Eu tive um pouco de dificuldade ao usar o código do @ john-myczek com um TextBox encadernado. Como o TextBox não gera um evento de foco quando é atualizado, a marca d’água permanece visível sob o novo texto. Para corrigir isso, simplesmente adicionei outro manipulador de events:

 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 – Eu realmente gosto da simplicidade da sua solução, mas minha reputação ainda não é alta o suficiente para você.

@Tim Murphy – Que “binding bidirecional requer caminho ou XPath” erro foi uma correção fácil … código atualizado, incluindo alguns outros pequenos ajustes (apenas WPF testado):

 using System; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Media; public class TextBoxWatermarked : TextBox { public string Watermark { get { return (string)GetValue(WaterMarkProperty); } set { SetValue(WaterMarkProperty, value); } } public static readonly DependencyProperty WaterMarkProperty = DependencyProperty.Register("Watermark", typeof(string), 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 (String.IsNullOrEmpty(Text) && !String.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 tem um exemplo mais complicado de uma “checkbox de pesquisa” completa aqui .

Se você está escrevendo aplicativos UWP no Windows 10, isso é muito mais fácil.

Mais informações: https://msdn.microsoft.com/pt-br/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 = string.Empty; } } private void txtData1_LostFocus(object sender, RoutedEventArgs e) { if (txtData1.Text == string.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 = (string) values[0]; return text == string.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 (string), typeof (ShadowedTextBox), new UIPropertyMetadata(string.Empty)); public static readonly DependencyProperty TextProperty = DependencyProperty.Register("Text", typeof (string), typeof (ShadowedTextBox), new UIPropertyMetadata(string.Empty)); public static readonly DependencyProperty TextChangedProperty = DependencyProperty.Register("TextChanged", typeof (TextChangedEventHandler), typeof (ShadowedTextBox), new UIPropertyMetadata(null)); public string Watermark { get { return (string)GetValue(WatermarkProperty); } set { SetValue(WatermarkProperty, value); } } public string Text { get { return (string) 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 (string.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 (string.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

Como funciona:

  • 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 strings in the DataTrigger.

 public class NotEmptyConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { var s = value as string; return string.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 String username = ""; private void usernameTextBox_GotFocus(object sender, RoutedEventArgs e) { if (String.IsNullOrEmpty(username)) { usernameTextBox.Text = ""; } } private void usernameTextBox_LostFocus(object sender, RoutedEventArgs e) { username = usernameTextBox.Text; if (String.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 String Value { get; set; } public String 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 (String.IsNullOrEmpty(this.Text)) { this.Text = PlaceholderText; this.Foreground = PlaceholderBrush; } } protected override void OnGotFocus(System.Windows.RoutedEventArgs e) { this.Foreground = ValuedBrush; if (String.IsNullOrEmpty(Value)) { this.Text = ""; } base.OnGotFocus(e); } protected override void OnLostFocus(System.Windows.RoutedEventArgs e) { Value = this.Text; if (String.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 == string.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 string, 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 = (string)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 trigger 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 (string), typeof (HintBehavior) //, new FrameworkPropertyMetadata(null, OnHintChanged) ); public string Hint { get { return (string) 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.