How to show placeholder text in a WPF TextBox in C# and VB
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:
How to show placeholder text in a WPF TextBox
<TextBox x:Name="txtSearch"/>
<Label x:Name="txtSearchPlaceholder" Content="Search..." Background="Transparent" Opacity="0.5" IsHitTestVisible="False"/>
private void txtSearch_TextChanged(Object sender, TextChangedEventArgs e)
{
if (txtSearch.Text != "") {
txtSearchPlaceholder.Visibility
= Visibility.Hidden;
} else {
txtSearchPlaceholder.Visibility
= Visibility.Visible;
}
}
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
<TextBox x:Name="txtSearch" TextChanged="txtSearch_TextChanged"/>
A cleaner approach would be to bind the visibility of the placeholder label to the Text property of the textbox with a data converter that returns Hidden when the bound value contains text and Visible when it is empty. This eliminates the need for the Texchanged codebehind.
ReplyDeleteYep, this option could work as well and would make it cleaner.
Delete