Well, that was fun. I went all the way around my elbow to get to my nose on UWP TextBox scrollbars. I figured out how to set it in XAML pretty quickly, but for some reason spaced on getting it working programmatically.

In XAML, things looked like this:

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <TextBox
        AcceptsReturn="True"
        ScrollViewer.VerticalScrollBarVisibility="Auto"
        ScrollViewer.HorizontalScrollBarVisibility="Auto"
        Name="txt"></TextBox>
</Grid>

So naturally I thought I should be able to do something like this in code... (To be clear, the following doesn't work, though, in my defense, it apparently used to in Silverlight)

// ... where `this` is, obviously, the TextBox. We're in the constructor right now.
this.HorizontalScrollBarVisibility = ScrollBarVisibility.Visible;
this.VerticalScrollBarVisibility = ScrollBarVisibility.Visible;

Or, maybe, at worst, this:

this.ScrollBarVisibility.HorizontalScrollBarVisibility = ScrollBarVisibility.Visible;
this.ScrollBarVisibility.VerticalScrollBarVisibility = ScrollBarVisibility.Visible;

Nope, no dice at all.

Hey me, it turns out that's the wrong idiom, you idiot! After going all the way through putting the stupid TextBox into its own ScrollViewer, and then managing scrolling by coordinating SizeChanged events in the TextBox (wait, whaaa?), I stumbled onto this MSDN page, which I'm suspicious I'd found before, which had the secret incantation for UWP TextBoxen:

TL;DR -- Here's the answer...

ScrollViewer.SetVerticalScrollBarVisibility(this, ScrollBarVisibility.Auto);
ScrollViewer.SetHorizontalScrollBarVisibility(this, ScrollBarVisibility.Auto);

That's a weird idiom for me, though it's essentially the same thing you do when you set rows and columns for Grids...

TextBox txtMd = new TextBox();
Grid.SetRow(txtMd, 1);
Grid.SetRowSpan(txtMd, 2);
Grid.SetColumnSpan(txtMd, 1);
grid.Children.Add(txtMd);

I'd expect each SetRow and SetRowSpan to be methods on the individual grid instantiations rather than a static method on Grid proper.

And it's not like the start of the text on the MSDN page helped a ton... It starts by making you think you have to manage this all yourself. Maybe it changed later? Nah, I'm sure I missed the answer a half-inch below.

A multi-line TextBox will continue to grow vertically as text is entered unless itโ€™s constrained by its Height or MaxHeight property, or by a parent container. You should test that a multi-line TextBox doesnโ€™t grow beyond its visible area, and constrain its growth if it does.

Oh well. Live and learn. Man, I made that tougher than it shoulda been.

Labels: , , ,