Click here to Skip to main content
15,867,835 members
Articles / Desktop Programming / WPF
Tip/Trick

WPF TextBox with Animated Overflow

Rate me:
Please Sign up or sign in to vote.
5.00/5 (7 votes)
8 Jul 2016MIT2 min read 13.8K   557   12  
A custom WPF TextBox whose height is animated when the text overflows.

Introduction

The WPF TextBox control doesn't have a built-in option for animating its Height property when the text overflows onto a new line (the same for the reverse).

Since I wanted this design feature for a software I'm working on, I created the AnimatedTextBox. Basically, it's not just a TextBox, but a Grid containing two of them : one is visible and the other is hidden.

Adding and removing text in the AnimatedTextBox

Background

Explanation :

  • This is the initial state. The red rectangle is the hidden TextBox, the blue one is the visible TextBox.
    The two TextBox(es) have the same height. When the user's writing in the AnimatedTextBox, he's writing in the blue one. So we are constantly copying the text in the visible TextBox into the hidden one.

    Initial state
  • If the AnimatedTextBox's TextWrapping property is set to Wrap, then this property has the same value for the two child TextBox(es). So they will wrap the text when it overflows. Here, the text of the hidden TextBox has overflowed, so the SizeChanged event is raised. But we impose a MaxHeight to the visible TextBox, so it stays at its current Height.

    Hidden TextBox's Height increased
  • Then we animate its Height until it has reached the actual Height of the hidden TextBox.

    Height animation to the hidden TextBox's Height
  • Here's the state when the animation is completed.

    Animation completed
  • Here's the same principle. Some text was deleted, so the Height of the hidden TextBox has decreased. The SizeChanged event is raised and we animate Height of the visible TextBox until it has reached the actual Height of the hidden TextBox.

    Animating to the hidden TextBox's decreased Height
  • Here's the state when the animation is completed.

    Animation completed

Using the code

Property Description
AnimationDuration Gets or sets the animation duration (in milliseconds).
IsAnimated Gets or sets a value indicating whether the AnimatedTextBox is animated.

Points of Interest

I'm just beginning with WPF and C#. I was programming in VB.NET with WinForms until now. So be indulgent with my approach. I just followed an idea that was given to me here on StackOverflow some days ago.

License

This article, along with any associated source code and files, is licensed under The MIT License



Comments and Discussions

 
-- There are no messages in this forum --