windows phone中,制作一个自定义的密码输入框控件,含图片,有水印,星号显示
最终结果:
关键点:
- 密码框中有图片之类的其他元素
- 在没有密码输入的时候,会显示诸如如图“密码”的水印
- 密码输入后,成“*”星号显示
新建一个控件,XAML代码如下:
<UserControl xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:toolkit="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls.Toolkit" x:Class="ewlan.PassWordBoxWithIcon" mc:Ignorable="d" FontFamily="{StaticResource PhoneFontFamilyNormal}" FontSize="{StaticResource PhoneFontSizeNormal}" Foreground="{StaticResource PhoneForegroundBrush}" d:DesignWidth="480" Height="60" Width="400"> <Grid x:Name="LayoutRoot" Background="{StaticResource TransparentBrush}"> //用一个border实现外面的灰色边框 <Border BorderBrush="#FFBFBFBF" BorderThickness="2" Margin="0"> <StackPanel Orientation="Horizontal"> <Grid Margin="10,0,0,0"> <Image Name="rememberPassword" HorizontalAlignment="Center" Source="/Images/password_icon.png" Stretch="None" VerticalAlignment="Center" Margin="0"/> <Image Name="forgetPassword" Visibility="Collapsed" HorizontalAlignment="Center" Source="/Images/password_unlock_icon.png" Stretch="None" VerticalAlignment="Center" Margin="0"/> </Grid> <Grid Width="351"> //1.PhoneTextBox实现水印效果 //2.PasswordBox实现密码输入变成“*”号效果 //3.两个控件做到大小一致,为什么?一会再看! <toolkit:PhoneTextBox Hint="静态密码" x:Name="passwordWatermark" Margin="0" FontSize="24" Width="270" HorizontalAlignment="Left" BorderThickness="0" Height="70" VerticalAlignment="Center"/> <PasswordBox KeyDown="passwdInput_KeyDown" Margin="0" x:Name="passwdInput" MaxLength="20" LostFocus="PasswordLostFocus" Opacity="0" GotFocus="PasswordGotFocus" Password="{Binding Password, Mode=TwoWay}" FontSize="24" Width="270" HorizontalAlignment="Left" BorderThickness="0" Height="70" VerticalAlignment="Center"/> </Grid> </StackPanel> </Border> </Grid> </UserControl>以下是CS代码:
public partial class PassWordBoxWithIcon : UserControl { public PassWordBoxWithIcon() { InitializeComponent(); passWordBoxWithIconInstance = this; } //在手指头离开密码输入框后,检查水印显示逻辑 private void PasswordLostFocus(object sender, RoutedEventArgs e) { CheckPasswordWatermark(); } public void CheckPasswordWatermark() { //发现用户没有输入,则将PasswordBox置于透明,PhoneTextBox置于100%不透明,以显示水印 //用户有输入,则相反,目的是用户不再看到水印! var passwordEmpty = string.IsNullOrEmpty(passwdInput.Password.Trim()); passwordWatermark.Opacity = passwordEmpty ? 100 : 0; passwdInput.Opacity = passwordEmpty ? 0 : 100; } private void PasswordGotFocus(object sender, RoutedEventArgs e) { //用户触摸获得焦点时,我们让passwordbox显现出来,以供输入! passwordWatermark.Opacity = 0; passwdInput.Opacity = 100; } }
聪明的你肯定明白了,好,就此结束!