Tuesday, June 10, 2014

WPF WaterMark Textbox to show PlaceHolder Text

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

How it works:
When textbox has a value, background set to White to cover up PlaceHolder text.
When textbox is empty, background becomes Transparent to show PlaceHolder text.

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

    <Grid>
        <Grid.Resources>
            <ux:NotEmptyConverter x:Key="NotEmptyConverter" />
            
            <Style TargetType="{x:Type Control}" x:Key="DefaultStyle">
                <Setter Property="FontSize" Value="20" />
                <Setter Property="Margin" Value="10"/>
                <Setter Property="VerticalAlignment" Value="Center"></Setter>
                <Setter Property="VerticalContentAlignment" Value="Center"></Setter>
            </Style>
 
            <Style TargetType="{x:Type TextBox}" BasedOn="{StaticResource DefaultStyle}"></Style>
 
        </Grid.Resources>
 
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>
        <TextBox Grid.Row="0" Text="Placeholder Text Is Here" Foreground="DarkGray" />
        <TextBox Grid.Row="0" Name="TextBoxEdit" 
                Text="{Binding Path=FirstName, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" >
            <TextBox.Style>
                <Style TargetType="{x:Type TextBox}" BasedOn="{StaticResource DefaultStyle}">
                    <Style.Triggers>
                        <DataTrigger Binding="{Binding Path=FirstName.Length, FallbackValue=0, TargetNullValue=0}" Value="0">
                            <Setter Property="Background" Value="Transparent"/>
                        </DataTrigger>
                        <DataTrigger Binding="{Binding Path=FirstName, FallbackValue=0, TargetNullValue=0, Converter={StaticResource NotEmptyConverter}}" Value="false">
                            <Setter Property="Background" Value="White"/>
                        </DataTrigger>
                    </Style.Triggers>
                </Style>
            </TextBox.Style>
        </TextBox>
    </Grid>

// Corresponding value converter to detect non-empty string

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

No comments:

Post a Comment