检查 PasswordBox 值 WPF

check PasswordBox Value WPF

我有一个密码框,但我也有一个文本块作为控件模板中的提示文本。当密码框有值时,我希望将其删除。我已经在下面尝试过,但它不起作用,我该怎么做?

简化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>

代码隐藏:

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

它说这个名字'HintTextBlock does not exist in the current context'

因为文本框 HintTextBlockPassworkBox 模板的一部分,所以不能直接访问它,因为它不是 window 直接控制的一部分。使用 FindName 查找密码框模板中的控件。

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