Behavior:行为,是WPF中一种用于扩展控件的一种机制。
DependencyProperty:依赖属性,是WPF的一个核心概念,可用于向控件传递数据,数据绑定,数据校验等。
实现步骤:
-
在工程中添加引用System.Windows.Interactivity,以支持behavior
-
创建作用于TextBox上的Behavior类文件TextBoxWatermarkBehavior.cs,在其头部使用命名空间:
using System.Windows.Interactivity;
- TextBoxWatermarkBehavior类的代码如下:
public class TextBoxWatermarkBehavior : Behavior<TextBox>
{
public static readonly DependencyProperty WatermarkProperty;
static TextBoxWatermarkBehavior()
{
WatermarkProperty = DependencyProperty.Register("Watermark", typeof(string), typeof(TextBoxWatermarkBehavior), new PropertyMetadata(default(string)));
}
bool _hasContent = false;
protected override void OnAttached()
{
base.OnAttached();
var textBox = AssociatedObject;
textBox.Loaded += (o, e) =>
{
if (!string.IsNullOrEmpty(textBox.Text))
{
_hasContent = true;
}
else
{
_hasContent = false;
if (!String.IsNullOrEmpty(Watermark))
{
textBox.Foreground = Brushes.Gray;
textBox.Text = Watermark;
textBox.GotFocus += TextBox_GotFocus;
textBox.LostFocus += TextBox_LostFocus;
}
}
};
}
private void TextBox_LostFocus(object sender, RoutedEventArgs e)
{
var textBox = sender as TextBox;
if (string.IsNullOrEmpty(textBox.Text))
{
_hasContent = false;
if (!string.IsNullOrEmpty(Watermark))
{
textBox.Text = Watermark;
textBox.Foreground = Brushes.Gray;
}
}
else
{
_hasContent = true;
}
}
private void TextBox_GotFocus(object sender, RoutedEventArgs e)
{
var textBox = sender as TextBox;
if (!string.IsNullOrEmpty(Watermark) && !_hasContent)
{
textBox.Text = "";
textBox.Foreground = Brushes.Black;
}
}
public string Watermark
{
get
{
return GetValue(WatermarkProperty) as string;
}
set
{
SetValue(WatermarkProperty, value);
}
}
protected override void OnDetaching()
{
base.OnDetaching();
}
}
测试Watermark, MainWindow.xaml:
<Window
x:Class="WpfApp2.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:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:local="clr-namespace:WpfApp2"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
Title="MainWindow"
Width="300"
Height="200"
mc:Ignorable="d">
<Grid Margin="20">
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="60" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Grid.Row="0" Grid.Column="0" VerticalAlignment="Center">无水印</TextBlock>
<TextBox Grid.Row="0" Grid.Column="1" Height="30" HorizontalAlignment="Stretch" />
<TextBlock Grid.Row="1" Grid.Column="0" VerticalAlignment="Center">有水印</TextBlock>
<TextBox Grid.Row="1" Grid.Column="1" Height="30">
<i:Interaction.Behaviors>
<local:TextBoxWatermarkBehavior Watermark="Please input" />
</i:Interaction.Behaviors>
</TextBox>
</Grid>
</Window>
最终效果:
Animation1111.gif
网友评论