csharp Copy code
public static class TextBoxPlaceholderHelper
{
public static readonly DependencyProperty PlaceholderProperty =
DependencyProperty.RegisterAttached("Placeholder", typeof(string), typeof(TextBoxPlaceholderHelper), new PropertyMetadata(string.Empty, OnPlaceholderChanged));
private static readonly DependencyProperty PlaceholderTextBlockProperty =
DependencyProperty.RegisterAttached("PlaceholderTextBlock", typeof(TextBlock), typeof(TextBoxPlaceholderHelper), new PropertyMetadata(null));
public static string GetPlaceholder(DependencyObject obj)
{
return (string)obj.GetValue(PlaceholderProperty);
}
public static void SetPlaceholder(DependencyObject obj, string value)
{
obj.SetValue(PlaceholderProperty, value);
}
private static TextBlock GetPlaceholderTextBlock(DependencyObject obj)
{
return (TextBlock)obj.GetValue(PlaceholderTextBlockProperty);
}
private static void SetPlaceholderTextBlock(DependencyObject obj, TextBlock value)
{
obj.SetValue(PlaceholderTextBlockProperty, value);
}
private static void OnPlaceholderChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var textBox = d as TextBox;
if (textBox == null) return;
var placeholderTextBlock = GetPlaceholderTextBlock(textBox);
if (placeholderTextBlock == null)
{
placeholderTextBlock = new TextBlock
{
IsHitTestVisible = false,
Focusable = false,
FontStyle = FontStyles.Italic,
Foreground = new SolidColorBrush(Colors.Gray),
Margin = new Thickness(2),
VerticalAlignment = VerticalAlignment.Center,
Visibility = Visibility.Collapsed
};
SetPlaceholderTextBlock(textBox, placeholderTextBlock);
textBox.Loaded += (s, args) =>
{
var border = VisualTreeHelper.GetChild(textBox, 0) as Border;
if (border == null) return;
var grid = border.Child as Grid;
if (grid == null) return;
grid.Children.Add(placeholderTextBlock);
};
textBox.GotFocus += (s, args) => UpdatePlaceholder(textBox);
textBox.LostFocus += (s, args) => UpdatePlaceholder(textBox);
textBox.TextChanged += (s, args) => UpdatePlaceholder(textBox);
}
placeholderTextBlock.Text = e.NewValue as string;
UpdatePlaceholder(textBox);
}
private static void UpdatePlaceholder(TextBox textBox)
{
var placeholderTextBlock = GetPlaceholderTextBlock(textBox);
if (placeholderTextBlock == null) return;
placeholderTextBlock.Visibility = string.IsNullOrEmpty(textBox.Text) && !textBox.IsFocused
? Visibility.Visible
: Visibility.Collapsed;
}
}