using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
namespace GsConfigTool.Helpers;
public static class PlaceholderHelper
{
public static readonly DependencyProperty PlaceholderProperty =
DependencyProperty.RegisterAttached(
"Placeholder",
typeof(string),
typeof(PlaceholderHelper),
new PropertyMetadata(string.Empty, OnPlaceholderChanged));
public static string GetPlaceholder(DependencyObject obj) =>
(string)obj.GetValue(PlaceholderProperty);
public static void SetPlaceholder(DependencyObject obj, string value) =>
obj.SetValue(PlaceholderProperty, value);
private static void OnPlaceholderChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (d is not TextBox tb) return;
tb.Loaded -= Tb_Loaded;
tb.Loaded += Tb_Loaded;
UpdatePlaceholder(tb);
}
private static void Tb_Loaded(object sender, RoutedEventArgs e)
{
if (sender is not TextBox tb) return;
tb.TextChanged -= Tb_TextChanged;
tb.TextChanged += Tb_TextChanged;
UpdatePlaceholder(tb);
}
private static void Tb_TextChanged(object sender, TextChangedEventArgs e)
{
if (sender is TextBox tb) UpdatePlaceholder(tb);
}
private static void UpdatePlaceholder(TextBox tb)
{
var placeholder = GetPlaceholder(tb);
if (string.IsNullOrEmpty(tb.Text))
{
if (!string.IsNullOrEmpty(placeholder))
tb.Tag = placeholder;
}
else
{
tb.Tag = null;
}
}
}