在WPF中,通过Style
实现TextBox中的水印文本(水印、提示、占位符文本)通常使用ControlTemplate
和VisualStateManager
。以下是一个详细的实例源代码:
using System.Windows;
using System.Windows.Controls;
namespace WpfWatermarkExample
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
}
public class WatermarkTextBox : TextBox
{
public static readonly DependencyProperty WatermarkProperty =
DependencyProperty.Register("Watermark", typeof(string), typeof(WatermarkTextBox));
public string Watermark
{
get { return (string)GetValue(WatermarkProperty); }
set { SetValue(WatermarkProperty, value); }
}
static WatermarkTextBox()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(WatermarkTextBox), new FrameworkPropertyMetadata(typeof(WatermarkTextBox)));
}
}
}
XAML文件:
<Window x:Class="WpfWatermarkExample.MainWindow"
xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="https://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="https://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Grid>
<local:WatermarkTextBox Watermark="请输入内容" Width="200" Height="30"/>
</Grid>
</Window>
Themes/Generic.xaml文件:
<ResourceDictionary xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfWatermarkExample">
<Style TargetType="{x:Type local:WatermarkTextBox}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:WatermarkTextBox}">
<Grid>
<TextBox x:Name="PART_TextBox"
Text="{TemplateBinding Text}"
VerticalAlignment="Center"
HorizontalAlignment="Stretch"/>
<TextBlock x:Name="PART_Watermark"
Text="{TemplateBinding Watermark}"
Foreground="Gray"
VerticalAlignment="Center"
HorizontalAlignment="Left"
Visibility="Collapsed"/>
</Grid>
<ControlTemplate.Triggers>
<MultiTrigger>
<MultiTrigger.Conditions>
<Condition Property="IsFocused" Value="False"/>
<Condition Property="Text" Value=""/>
</MultiTrigger.Conditions>
<Setter TargetName="PART_Watermark" Property="Visibility" Value="Visible"/>
</MultiTrigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>
看效果:
这个例子中,自定义了WatermarkTextBox
类,其中包含一个Watermark
属性。在Themes/Generic.xaml
中,定义了WatermarkTextBox
的ControlTemplate
,通过VisualStateManager
在未获得焦点且文本为空时显示水印文本。在MainWindow.xaml
中使用了WatermarkTextBox
并设置了水印文本。
源代码获取:公众号回复消息【code:89221
】