Style Trigger on Passwordbox

textbox, wpf

Solution

If you are using a `PasswordBox`, make sure to change the `TargetType` and use a `DataTrigger`:

<Style TargetType="{x:Type PasswordBox}" xmlns:sys="clr-namespace:System;assembly=mscorlib">
            <Style.Resources>
                <VisualBrush x:Key="CueBannerBrush" AlignmentX="Left" AlignmentY="Center" Stretch="None">
                    <VisualBrush.Visual>
                        <Label Content="Search" Foreground="LightGray"/>
                    </VisualBrush.Visual>
                </VisualBrush>
            </Style.Resources>
            <Style.Triggers>
                <DataTrigger Binding="{Binding Path=Password}" Value="{x:Null}">
                    <Setter Property="Background" Value="{StaticResource CueBannerBrush}" />
                </DataTrigger>

                <Trigger Property="IsKeyboardFocused" Value="True">
                    <Setter Property="Background" Value="White" />
                </Trigger>
            </Style.Triggers>
            <Setter Property="Control.Foreground" Value="#4C2C66"/>
            <Setter Property="VerticalAlignment" Value="Center"/>
       </Style>

Problem

I'm using the following style on a Textbox so that it has text and a background colour until someone tries to enter data into it. Works fine but my problem arises because it is a login screen and my other control is a Passwordbox which won't let me access the Password property (which is the equivalent to the Text property of the Textbox). Any advice on how I would work around this? ``` <Style TargetType="TextBox" xmlns:sys="clr-namespace:System;assembly=mscorlib"> <Style.Resources> <VisualBrush x:Key="CueBannerBrush" AlignmentX="Left" AlignmentY="Center" Stretch="None"> <VisualBrush.Visual> <Label Content="Search" Foreground="LightGray"/> </VisualBrush.Visual> </VisualBrush> </Style.Resources> <Style.Triggers> <Trigger Property="Text" Value="{x:Static sys:String.Empty}"> <Setter Property="Background" Value="{StaticResource CueBannerBrush}" /> </Trigger> <Trigger Property="Text" Value="{x:Null}"> <Setter Property="Background" Value="{StaticResource CueBannerBrush}" /> </Trigger> <Trigger Property="IsKeyboardFocused" Value="True"> <Setter Property="Background" Value="White" /> </Trigger> </Style.Triggers> <Setter Property="Control.Foreground" Value="#4C2C66"/> <Setter Property="VerticalAlignment" Value="Center"/> </Style> ```

Original source

Related problems