[Attached Property] WPF TextBox clears Text when user presses Escape key

To add the behavior to the WPF TextBox, use the following XAML.

<Window x:Class="WPF.MainWindow" 
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
        Title="WPF TextBox MVVM DataBinding Example" Height="500" Width="500"
         xmlns:Behaviors="clr-namespace:Behaviors">
    <Grid>
        <TextBox Behaviors:TextBoxBehavior.EscapeClearsText="True" />
    >
>


using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace  Behaviors
{
    public class TextBoxBehavior
    {
        #region Attached Property EscapeClearsText

        public static readonly DependencyProperty EscapeClearsTextProperty
           = DependencyProperty.RegisterAttached("EscapeClearsText"typeof(bool), typeof(TextBoxBehavior),
                new FrameworkPropertyMetadata(falsenew PropertyChangedCallback(OnEscapeClearsTextChanged)));

        private static void OnEscapeClearsTextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if ((bool)e.NewValue)
            {
                var textBox = d as TextBox;
                if (textBox != null)
                {
                    textBox.KeyUp -= TextBoxKeyUp;
                    textBox.KeyUp += TextBoxKeyUp;
                }
            }
        }

        private static void TextBoxKeyUp(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Escape)
            {
                ((TextBox) sender).Text = string.Empty;
            }
        }

        public static void SetEscapeClearsText(DependencyObject dependencyObject, bool escapeClearsText)
        {
            if (!ReferenceEquals(null, dependencyObject))
                dependencyObject.SetValue(EscapeClearsTextProperty, escapeClearsText);
        }

        public static bool GetEscapeClearsText(DependencyObject dependencyObject)
        {
            if (!ReferenceEquals(null, dependencyObject))
                return (bool)dependencyObject.GetValue(EscapeClearsTextProperty);
            return false;
        }

        #endregion Attached Property EscapeClearsText
    }
}

Comments

Popular posts from this blog

WPF How to Dispose ViewModel when the associated UserControl (Not Window) closes?

C# How to unit test Dispatcher

WPF: How to Deep Copy WPF object (e.g. UIElement) ?