A simple TrimmedTextBox for WPF

So I wanted a TextBox that trims automatically. At first I played with the idea of a converter, but that just didn’t work out. Try using a trim converter with UpdateSourceTrigger=PropertyChanged and you will see what I mean. Yes, it seems you cannot even type a space. I need the trimming to occur after losing focus.

After thinking about it, a converter was the wrong method anyway. If I want a TextBox that always trims when it loses focus, why not just make one by inheriting from TextBox and adding a method to the LostFocus event. So I did.

using System.Windows.Controls;

namespace WpfSharp.UserControls
    public class TrimmedTextBox : TextBox
        public TrimmedTextBox()
            LostFocus += TrimOnLostFocus;

        void TrimOnLostFocus(object sender, System.Windows.RoutedEventArgs e)
            var trimTextBox = sender as TrimmedTextBox;
            if (trimTextBox != null)
                trimTextBox.Text = trimTextBox.Text.Trim();

Now to use this in XAML, add this namespace to your UserControl or Window:


Then use the object like this:

<wpfsharp:TrimmedTextBox Name="TextBoxAccount" TextWrapping="Wrap" MinWidth="200" Text="{Binding Account}" />

Remember, it is the simple solutions that are best.

Leave a Reply