Inspired by Greg Shacles’ FloatLabeledEntry I wanted to see how easy (or hard) it was to bring similar effect to UWP apps. This is the result:
TextBox already has a header in its template which is always shown. This helps us and we don’t have to create custom control, we can just alter the default style. For the above effect, the header had to be hidden by default and shown once user starts typing. This can be done easily just by changing the animations in the visual states. We will change the default template for TextBox which can be easily extracted in Visual Studio.
First, change the
HeaderContentPresenter by setting the opacity to 0 and add
<ContentPresenter.RenderTransform> <TranslateTransform Y="25" /> </ContentPresenter.RenderTransform>
Now, we want to animate header once the user starts typing. To do that, edit the
Focused visual state and add the following animation:
<DoubleAnimation Storyboard.TargetName="HeaderContentPresenter" Storyboard.TargetProperty="Opacity" To="1" Duration="0:0:0.25" /> <DoubleAnimation Storyboard.TargetName="HeaderContentPresenter" Storyboard.TargetProperty="(UIElement.RenderTransform).(TranslateTransform.Y)" To="0" Duration="0:0:0.25" > <DoubleAnimation.EasingFunction> <SineEase EasingMode="EaseOut" /> </DoubleAnimation.EasingFunction> </DoubleAnimation>
And since we want the animation to reverse when the focus is lost, we should add transitions:
<VisualStateGroup.Transitions> <VisualTransition From="Focused" GeneratedDuration="0:0:0.1" /> </VisualStateGroup.Transitions>
And we are done. This is rather simplistic approach and we still need to tweak font properties a bit, maybe animate placeholder text as well. But that is left as an exercise for the reader. You can find the full code for the final style in gist https://gist.github.com/tpetrina/924dba9f93ebf105b221.