WPF实现TextBox水印效果
通常情况下,在使用文本框的时候,一般会在文本框上放一段水印文字,今天用WPF来实现一下
创建一个用户控件
一般像这种常用的,最好是自己写成用户控件,防止复制粘贴大量冗余代码
XAML:
<TextBox x:Class="CallCenter.UserControl.TipTextbox"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:CallCenter.UserControl"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800" Name="MyTextbox">
<TextBox.Background>
<VisualBrush Stretch="None" AlignmentX="Left">
<VisualBrush.Visual>
<Border DataContext="{Binding ElementName=MyTextbox}" Background="White" Width="{Binding ElementName=MyTextbox,Path=ActualWidth}"
Height="{Binding Path=ActualHeight}">
<TextBlock Text="{Binding ElementName=MyTextbox,Path=TipText}"
VerticalAlignment="{Binding ElementName=MyTextbox,Path=VerticalContentAlignment}">
<TextBlock.Style>
<Style TargetType="TextBlock">
<Setter Property="Opacity" Value="0"/>
<Style.Triggers>
<DataTrigger Binding="{Binding ElementName=MyTextbox,Path=Text}" Value="">
<Setter Property="Opacity" Value="0.2"/>
</DataTrigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
</TextBlock>
</Border>
</VisualBrush.Visual>
</VisualBrush>
</TextBox.Background>
</TextBox>
后台CS:
/// <summary>
/// TipTextbox.xaml 的交互逻辑
/// </summary>
public partial class TipTextbox : TextBox
{
public TipTextbox()
{
InitializeComponent();
}
public string TipText
{
get { return (string)GetValue(TipTextProperty); }
set { SetValue(TipTextProperty, value); }
}
public static readonly DependencyProperty TipTextProperty =
DependencyProperty.Register("TipText", typeof(string), typeof(TipTextbox), new PropertyMetadata(""));
}
引入命名空间
xmlns:uc="clr-namespace:CallCenter.UserControl"
使用自定义用户控件
<uc:TipTextbox TipText="请输入账号" Width="200" Height="30"/>