概述:WPF中通過`Style`實現TextBox水印文本,使用`WatermarkTextBox`類及`ControlTemplate`。這個示例通過`VisualStateManager`在文本框失去焦點且內容為空時顯示水印文本。通過`Watermark`屬性簡化水印文本設置,提高可維護性。 在 ...
概述:WPF中通過`Style`實現TextBox水印文本,使用`WatermarkTextBox`類及`ControlTemplate`。這個示例通過`VisualStateManager`在文本框失去焦點且內容為空時顯示水印文本。通過`Watermark`屬性簡化水印文本設置,提高可維護性。
在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="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"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Grid>
<local:WatermarkTextBox Watermark="請輸入內容" Width="200" Height="30"/>
</Grid>
</Window>
Themes/Generic.xaml文件:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://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並設置了水印文本。
源代碼獲取:https://pan.baidu.com/s/1YCuKZhEOrs-C3nGqjNB-lA?pwd=6666