Hardgraf
Hardgraf

Reputation: 2626

Trigger on Text.Length > 0

Trying to use a MultiDataTrigger to hide watermark text in a TextBox when TextBox.Length > 0

 <Style.Triggers>    
     <MultiDataTrigger>
         <MultiDataTrigger.Conditions>
              <Condition Binding="{Binding ElementName=SearchTermTextBox, UpdateSourceTrigger=PropertyChanged, Path=Text.Length}"
                                           Value="1"/>

                                <Condition Binding="{Binding IsMouseOver, ElementName=SearchTermTextBox, UpdateSourceTrigger=PropertyChanged}"
                                           Value="true"/>                                                          
                 </MultiDataTrigger.Conditions>
             <Setter Property="Visibility"
                     Value="Collapsed"/>
            </MultiDataTrigger>
     </Style.Triggers>

This works obviously only when the text.Length = 1. Is there an easy way to achieve this or do I need to write an implementation of IValueConverter?

Upvotes: 0

Views: 2540

Answers (1)

Rachel
Rachel

Reputation: 132548

What about doing the reverse? By default don't show watermark, and have your trigger show it when Text.Length = 0?

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfApplication1"
        x:Name="MyWindow"
        Title="MainWindow"
        Height="200" Width="400">

    <Window.Resources>
        <Style x:Key="TestTextStyle" TargetType="{x:Type TextBlock}">
            <Setter Property="Visibility" Value="Collapsed" />
            <Setter Property="Margin" Value="2" />
            <Setter Property="IsHitTestVisible" Value="False" />
            <Setter Property="Foreground" Value="Silver" />
            <Style.Triggers>
                <DataTrigger Binding="{Binding ElementName=SearchTermTextBox, UpdateSourceTrigger=PropertyChanged, Path=Text.Length}" Value="0">
                    <Setter Property="Visibility" Value="Visible" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </Window.Resources>

    <Grid Margin="10">
        <TextBox Name="SearchTermTextBox" />
        <TextBlock Style="{StaticResource TestTextStyle}" Text="Test Watermark" />
    </Grid>
</Window>

enter image description here enter image description here

Just be sure you set the initial Visibility=Collapsed as part of the Style, and not hardcoded into the <TextBlock /> tag, because DependencyProperty Precedence declares that all properties set in the <Tag> have a higher precedence than ones set in a Trigger, so the value will never change.

Upvotes: 1

Related Questions