0

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

简化的 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 在当前上下文中不存在'

4

1 回答 1

1

由于文本框HintTextBlock是模板的一部分,PassworkBox因此它不能直接访问,因为它不是窗口直接控制的一部分。使用 FindName 在密码框模板中查找控件。

TextBlock hintTextBlock = pwdBox.Template.FindName("HintTextBlock", pwdBox) as TextBlock;
if (pwdBox.SecurePassword.Length == 0)
    {
        hintTextBlock.Visiblility = Visiblitity.Visible;
    }
    else
    {
        hintTextBlock.Visiblility = Visiblility.Collapsed;
    }
于 2015-11-19T18:07:37.963 回答