wpf带水印的密码框样式
时间: 2023-10-23 14:37:21 浏览: 139
你可以通过自定义WPF样式来创建带水印的密码框。下面是一个示例样式,其中包含了带有水印的文本框和密码框:
```xml
<Style x:Key="WatermarkPasswordBox" TargetType="{x:Type PasswordBox}">
<Setter Property="Background" Value="White"/>
<Setter Property="BorderThickness" Value="1"/>
<Setter Property="BorderBrush" Value="#FF7F9DB9"/>
<Setter Property="Foreground" Value="Black"/>
<Setter Property="Padding" Value="2"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type PasswordBox}">
<Border BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" SnapsToDevicePixels="True">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<TextBox x:Name="PART_TextBox" Grid.Column="0" Foreground="{TemplateBinding Foreground}" Text="{TemplateBinding Password}" Margin="{TemplateBinding Padding}" VerticalContentAlignment="{TemplateBinding VerticalContentAlignment}" IsReadOnly="{TemplateBinding IsReadOnly}" IsEnabled="{TemplateBinding IsEnabled}" Background="Transparent"/>
<TextBlock x:Name="PART_Watermark" Grid.Column="0" Foreground="Gray" Text="Password" Margin="{TemplateBinding Padding}" VerticalAlignment="Center" Visibility="Collapsed"/>
<ToggleButton x:Name="PART_ShowPasswordButton" Grid.Column="1" Width="20" Height="20" Style="{StaticResource ToggleButtonStyle}" IsChecked="{Binding IsChecked, ElementName=PART_ShowPasswordButton}" VerticalAlignment="Center" HorizontalAlignment="Right"/>
</Grid>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsFocused" Value="True">
<Setter Property="Visibility" TargetName="PART_Watermark" Value="Collapsed"/>
</Trigger>
<Trigger Property="IsEnabled" Value="False">
<Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.GrayTextBrushKey}}"/>
<Setter Property="Background" Value="#FFF4F4F4"/>
</Trigger>
<DataTrigger Binding="{Binding IsChecked, ElementName=PART_ShowPasswordButton}" Value="True">
<Setter TargetName="PART_TextBox" Property="Visibility" Value="Collapsed"/>
<Setter TargetName="PART_Watermark" Property="Visibility" Value="Visible"/>
</DataTrigger>
<DataTrigger Binding="{Binding IsChecked, ElementName=PART_ShowPasswordButton}" Value="False">
<Setter TargetName="PART_TextBox" Property="Visibility" Value="Visible"/>
<Setter TargetName="PART_Watermark" Property="Visibility" Value="Collapsed"/>
</DataTrigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
```
在这个样式中,使用了一个文本框控件和一个密码框控件来创建带有水印的密码框。水印文本是在TextBox控件上覆盖了一个TextBlock控件实现的,当用户输入密码时,水印文本会被隐藏。此外,还添加了一个ToggleButton控件,用于显示或隐藏密码。
使用这个样式时,只需要将PasswordBox控件的样式设置为WatermarkPasswordBox即可。例如:
```xml
<PasswordBox Style="{StaticResource WatermarkPasswordBox}"/>
```
这样就可以创建一个带有水印的密码框了。
阅读全文