How to show placeholder text in a WPF textbox

Sometimes, when you have a text box in a user interface, you may want to add placeholder text to that text box to give users a prompt as to what to enter into the text box. If you've ever used UWP or WinUI, you'll probably have noticed that the default text box elements provide a PlaceholderText property that provides this functionality. However, WPF and Windows Forms don't provide this functionality by default. Luckily, thanks to WPF's rendering capabilities, it is quite easy to set up placeholder text manually. If you're using Windows Forms, you can make use of the ElementHost to use a WPF TextBox. Typically, placeholder text is a slightly faded colour compared to user-entered text to help distinguish it and only shows when no text is entered into the text box. An example is below:

WPF TexBox with placeholder text

How to show placeholder text in a WPF TextBox

To show placeholder text in a WPF textbox, all we need to do is show a partially transparent, intangible Label above the TextBox like so (You can replace 'Search...' with your own placeholder test):

<TextBox x:Name="txtSearch"/>

<Label x:Name="txtSearchPlaceholder" Content="Search..." Background="Transparent" Opacity="0.5" IsHitTestVisible="False"/>


Note: This XAML should be pasted within a grid or other element that allows the Label to show on top of the TextBox.
This will show the placeholder text, however, the text will remain there even when the user types in the TextBox. To have the placeholder text only show when there's no text in the TextBox, we need code like this:

C#:

private void txtSearch_TextChanged(Object sender, TextChangedEventArgs e)

{

if (txtSearch.Text != "") {

     txtSearchPlaceholder.Visibility

= Visibility.Hidden;

} else {

    txtSearchPlaceholder.Visibility

= Visibility.Visible;

}

}

VB:

Private Sub txtSearch_TextChanged(sender As Object, e As TextChangedEventArgs)

If txtSearch.Text <> "" Then

txtSearchPlaceholder.Visibility = Visibility.Hidden

Else

txtSearchPlaceholder.Visibility = Visibility.Visible

End If

End Sub


Then be sure to add the event handler to XAML:

<TextBox x:Name="txtSearch" TextChanged="txtSearch_TextChanged"/> 


Did this article help you? Do you have any suggestions for a better way to achieve this? Let us know in the comments.

This snippet is available in Codly. Click the appropriate link below to download the snippet. If you don't have Codly, it is available here in the Microsoft Store.


Follow us to be notified when we release new guides:

Comments

Popular posts from this blog

How to enable dark title bar in Windows Forms and WPF (Windows Presentation Foundation) apps

How to enable precision scrolling in a WPF app on Windows