How do you scroll to the bottom of a TextBox for a UWP app?
With my transition to UWP, this has been one of the questions that hasn\'t been straight-forward.
If anyone needs to scroll to the bottom of a TextBox in UWP apps:
https://code.msdn.microsoft.com/windowsapps/How-to-scroll-to-the-a8ea5867
private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{
var grid = (Grid)VisualTreeHelper.GetChild(textBox1, 0);
for (var i = 0; i <= VisualTreeHelper.GetChildrenCount(grid) - 1; i++)
{
object obj = VisualTreeHelper.GetChild(grid, i);
if (!(obj is ScrollViewer)) continue;
((ScrollViewer)obj).ChangeView(0.0f, ((ScrollViewer)obj).ExtentHeight, 1.0f);
break;
}
}
}
where textBox1 is the TextBox you want to scroll to the bottom.
Using the answer from https://code.msdn.microsoft.com/windowsapps/How-to-scroll-to-the-a8ea5867 sometimes caused lines to be deleted when scrolling up.
To fix that, try this:
private void ScrollToBottom(TextBox textBox)
{
var grid = (Grid)VisualTreeHelper.GetChild(textBox, 0);
for (var i = 0; i <= VisualTreeHelper.GetChildrenCount(grid) - 1; i++)
{
object obj = VisualTreeHelper.GetChild(grid, i);
if (!(obj is ScrollViewer)) continue;
((ScrollViewer)obj).ChangeView(0.0f, ((ScrollViewer)obj).ExtentHeight, 1.0f, true);
break;
}
}
The main difference is this line:
((ScrollViewer)obj).ChangeView(0.0f, ((ScrollViewer)obj).ExtentHeight, 1.0f, true);
I also separated the method from the event handler, because I didn't want to necessarily scroll every time the text was changed.
An equivalent to the previous answer in C++/CX:
using Windows::UI::Xaml::Media::VisualTreeHelper;
using Windows::UI::Xaml::Controls::Grid;
using Windows::UI::Xaml::Controls::ScrollViewer;
using Platform::Object;
void
MainPage::responseTextUpdated(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
{
Grid^ grid = static_cast<Grid^>(VisualTreeHelper::GetChild(responseText, 0));
for (int i = 0; i < VisualTreeHelper::GetChildrenCount(grid); ++i)
{
Object^ child = VisualTreeHelper::GetChild(grid, i);
ScrollViewer^ scrollViewer = dynamic_cast<ScrollViewer^>(child);
if (scrollViewer == nullptr) continue;
double const horizontalOffset = 0;
double const verticalOffset = scrollViewer->ExtentHeight;
float const zoomFactor = 1;
scrollViewer->ChangeView(horizontalOffset, verticalOffset, zoomFactor);
break;
}
}
Where responseText is TextBox^ responseText
, the TextBox you want to scroll (probably the same as sender).