[WPF] TextBoxにPlaceholderを追加する

Placeholderをつけてくれーと言われて、添付プロパティを用意したのでメモ。

できるだけ簡易的に。

スポンサーリンク

添付プロパティ

using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

public static class TextBoxHelper
{
    public static readonly DependencyProperty PlaceholderProperty = DependencyProperty.RegisterAttached(
        "Placeholder", typeof(string), typeof(TextBoxHelper), new PropertyMetadata(string.Empty, OnPlaceholderChanged));

    public static string GetPlaceholder(DependencyObject obj)
    {
        return (string)obj.GetValue(PlaceholderProperty);
    }

    public static void SetPlaceholder(DependencyObject obj, string value)
    {
        obj.SetValue(PlaceholderProperty, value);
    }

    public static void OnPlaceholderChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
    {
        if (obj is TextBox textBox)
        {
            textBox.Loaded += (sender, args) => ShowPlaceholder(textBox);
            textBox.GetFocus += (sender, args) => HidePlaceholder(textBox);
            textBox.LostFocus += (sender, args) => ShowPlaceholder(textBox);
        }
    }

    private static void ShowPlaceholder(TextBox textBox)
    {
        if (string.IsNullOrEmpty(textBox.Text))
        {
            textBox.Text = GetPlaceholder(textBox);
            textBox.Foreground = Brushes.Gray;
        }
    }

    private static void HidePlaceholder(TextBox textBox)
    {
        if (textBox.Text == GetPlaceholder(textBox))
        {
            textBox.Text = string.Empty;
            textBox.Foreground = Brushes.Black;
        }
    }
}

使い方

Xaml側でTextBoxへ添付プロパティを設定して動作させます。

<TextBox local:TextBoxHelper.Placeholder="sample text" />

参考資料

おしまい。

スポンサーリンク

.NET,C#,MFC.NET,C#,WPF

Posted by peliphilo