WPF | VB .Net || Textbox Placeholder

766 Views Asked by At

i want to have a placeholder in my textbox in wpf.. i tried to search xaml script to solve my problem, and i find that xaml codes are too long for simple placeholder, then i end up with my own solution.. is event handlers will slow down an app?

Dim myPlaceholder As String = "My Sample Placeholder"

Private Sub tbStarSign_GotFocus(sender As Object, e As RoutedEventArgs) Handles tbStarSign.GotFocus
    If tbStarSign.Text = myPlaceholder Then
        tbStarSign.Text = ""
    End If
End Sub

Private Sub tbStarSign_LostFocus(sender As Object, e As RoutedEventArgs) Handles tbStarSign.LostFocus
    If tbStarSign.Text = "" Then
        tbStarSign.Text = myPlaceholder
    End If
End Sub

.

1

There are 1 best solutions below

1
On BEST ANSWER

There's nothing wrong with a XAML only solution.

<Style TargetType="TextBox" BasedOn="{StaticResource {x:Type TextBox}}"
       x:Key="TextBoxWithWatermarkStyle">
    <Setter Property="Padding" Value="3"/>
    <Setter Property="Background" Value="White"/>
    <Setter Property="Foreground" Value="Black"/>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="TextBox">
                <Border BorderThickness="1"
                        CornerRadius="1"
                        Background="{TemplateBinding Background}">
                    <Grid>
                        <ScrollViewer Margin="{TemplateBinding Padding}"
                                  x:Name="PART_ContentHost"/>
                        <TextBlock IsHitTestVisible="False" 
                               Text="{TemplateBinding Tag}"
                               VerticalAlignment="Center" 
                               HorizontalAlignment="Left"
                               Opacity="0.25"
                               Foreground="{TemplateBinding Foreground}"
                               Margin="5,0,0,0">
                            <TextBlock.Style>
                                <Style TargetType="{x:Type TextBlock}">
                                    <Setter Property="Visibility" Value="Collapsed"/>
                                    <Style.Triggers>
                                        <DataTrigger Binding="{Binding Text, RelativeSource={RelativeSource TemplatedParent}}" Value="">
                                            <Setter Property="Visibility" Value="Visible"/>
                                        </DataTrigger>
                                    </Style.Triggers>
                                </Style>
                            </TextBlock.Style>
                        </TextBlock>
                    </Grid>
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

Usage:

<TextBox Style="{StaticResource TextBoxWithWatermarkStyle}" Tag="Hello world" ... />