wpf带水印的密码框样式
时间: 2023-10-23 22:37:20 浏览: 167
WPF带水印的输入框
要自定义带水印的密码框的样式,需要重写 PasswordBox 控件的 ControlTemplate。以下是一个示例,您可以根据自己的需求进行修改:
```xaml
<Style x:Key="WatermarkPasswordBox" TargetType="{x:Type PasswordBox}">
<Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}" />
<Setter Property="Background" Value="{DynamicResource {x:Static SystemColors.WindowBrushKey}}" />
<Setter Property="BorderBrush" Value="{DynamicResource {x:Static SystemColors.ActiveBorderBrushKey}}" />
<Setter Property="BorderThickness" Value="1" />
<Setter Property="Padding" Value="2" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type PasswordBox}">
<Grid>
<Border x:Name="border" Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}">
<Grid>
<PasswordBox x:Name="PART_PasswordBox" Margin="2" Background="Transparent" BorderThickness="0" />
<TextBlock x:Name="PART_Watermark" Text="{TemplateBinding Tag}" Margin="2" VerticalAlignment="Center" Foreground="LightGray" Visibility="{Binding Path=Password.Length, ElementName=PART_PasswordBox, Converter={StaticResource IntToVisibilityConverter}}" />
</Grid>
</Border>
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="IsEnabled" Value="False">
<Setter TargetName="border" Property="Opacity" Value="0.56" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
```
在上面的样式中,我们重写了 PasswordBox 的 ControlTemplate。我们使用一个 Border 控件来包裹 PasswordBox 和 TextBlock 控件,并使用 Tag 属性来绑定水印的文本。使用 Visibility 绑定 PasswordBox 的 Password 属性的长度,如果长度为 0,显示水印。
如果需要自定义水印的样式,您可以修改 TextBlock 的样式,例如:
```xaml
<TextBlock x:Name="PART_Watermark" Text="{TemplateBinding Tag}" Margin="2" VerticalAlignment="Center" Foreground="LightGray" Visibility="{Binding Path=Password.Length, ElementName=PART_PasswordBox, Converter={StaticResource IntToVisibilityConverter}}">
<TextBlock.Style>
<Style TargetType="TextBlock">
<Setter Property="FontStyle" Value="Italic" />
</Style>
</TextBlock.Style>
</TextBlock>
```
最后,您可以在需要使用带水印的密码框的地方使用上面的样式:
```xaml
<PasswordBox Style="{StaticResource WatermarkPasswordBox}" Tag="Enter password..." />
```
希望这个示例对您有所帮助!
阅读全文