Search code examples
c#wpfxamltextblockpasswordbox

check PasswordBox Value WPF


I have a password box, but i also have a textblock as hint text within the control template. I'd like this to be removed when the password box has a value. I have tried this below but it doesn't work, how can I do this?

Simplified XAML :

<PasswordBox Height="20" Name="pwdBox" PasswordChanged="pwdBox_PasswordChanged" Style="{DynamicResource PasswordBoxStyle1}"/>

<Style x:Key="PasswordBoxStyle1" TargetType="{x:Type PasswordBox}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type PasswordBox}">
                <Border x:Name="Border" .. >
                    <StackPanel ..>
                        <TextBlock x:Name="LabelTextBlock" ...
                            Text="Password Label"  />
                        <Grid>
                            <ScrollViewer x:Name="PART_ContentHost"
                                Focusable="false"
                                HorizontalScrollBarVisibility="Hidden"
                                VerticalScrollBarVisibility="Hidden"/>
                            <TextBlock x:Name="HintTextBlock"
                                Focusable="False"
                                IsHitTestVisible="False"
                                Opacity="0"
                                Text="Enter Your Password" />
                        </Grid>
                    </StackPanel>
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

Code Behind :

private void pwdBox_PasswordChanged(object sender, RoutedEventArgs e)
{
    if (pwdBox.SecurePassword.Length == 0)
    {
        HintTextBlock.IsVisible = true;
    }
    else
    {
        HintTextBlock.IsVisible = false;
    }
}

It says that the name 'HintTextBlock does not exist in the current context'


Solution

  • Since, the text box HintTextBlock is part of Template of PassworkBox so it can not accessed directly as it is not part of direct control of window. Use the FindName to find the control in template of passwordbox.

    TextBlock hintTextBlock = pwdBox.Template.FindName("HintTextBlock", pwdBox) as TextBlock;
    if (pwdBox.SecurePassword.Length == 0)
        {
            hintTextBlock.Visiblility = Visiblitity.Visible;
        }
        else
        {
            hintTextBlock.Visiblility = Visiblility.Collapsed;
        }