我写了一个PasswordBox风格。我想在密码框中做提示文本,但是当丢失焦点时,提示文本正在显示。我在哪里做错了,我该如何解决这个问题?
这是代码:
<Style TargetType="{x:Type PasswordBox}" xmlns:sys="clr-namespace:System;assembly=mscorlib">
<Style.Resources>
<VisualBrush x:Key="Bg1" AlignmentX="Center" AlignmentY="Center" Stretch="None" >
<VisualBrush.Visual>
<Label Content="Enter password" Foreground="LightGray" Margin="5,0,0,0"/>
</VisualBrush.Visual>
</VisualBrush>
<VisualBrush x:Key="Bg2" AlignmentX="Center" AlignmentY="Center" Stretch="None" >
<VisualBrush.Visual>
<Label Content="" Foreground="LightGray" Margin="5,0,0,0"/>
</VisualBrush.Visual>
</VisualBrush>
</Style.Resources>
<Setter Property="FontSize" Value="16"/>
<Setter Property="Foreground" Value="#FF585858"/>
<Setter Property="VerticalContentAlignment" Value="Center"/>
<Setter Property="HorizontalContentAlignment" Value="Center"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type PasswordBox}">
<Border CornerRadius="2" x:Name="border" Background="{TemplateBinding Background}" BorderThickness="1" BorderBrush="LightGray">
<ScrollViewer ScrollViewer.VerticalScrollBarVisibility="Visible" Margin="0" ScrollViewer.CanContentScroll="True" x:Name="PART_ContentHost"/>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsFocused" Value="True">
<Setter Property="BorderBrush" TargetName="border" Value="#FFD0D0D0"/>
<Setter Property="BorderThickness" TargetName="border" Value="2"/>
</Trigger>
<DataTrigger Binding="{Binding Path=Password}" Value="{x:Static sys:String.Empty}">
<Setter Property="Background" Value="{StaticResource Bg2}" />
</DataTrigger>
<DataTrigger Binding="{Binding Path=Password}" Value="{x:Null}">
<Setter Property="Background" Value="{StaticResource Bg1}" />
</DataTrigger>
<Trigger Property="IsKeyboardFocused" Value="True">
<Setter Property="Background" Value="White" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
感谢您的建议。
答案 0 :(得分:2)
出于某些安全原因,PasswordBox中的Password属性不是依赖属性。所以它不能在Trigger中使用。您为Password属性应用的触发器无效。这就是原因,即使您在其中包含有效文本,提示文本也会出现。无论密码是空还是NULL,只有IsKeyboardFocused上应用的触发器才有效。
以下文章必须给出一些好主意,为密码框实现水印,
http://prabu-guru.blogspot.in/2010/06/how-to-add-watermark-text-to-textbox.html
答案 1 :(得分:-1)