如何滚动到UWP应用的TextBox底部?
随着我向UWP的过渡,这是一直没有直截了当的问题。
我曾经能够使用它:
textBox.SelectionStart = textBox.TextLength;
textBox.ScrollToCaret();
但是,这对UWP应用程序不起作用
答案 0 :(得分:3)
使用https://code.msdn.microsoft.com/windowsapps/How-to-scroll-to-the-a8ea5867的答案有时会导致在向上滚动时删除行。
要解决此问题,请尝试以下方法:
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;
}
}
主要区别在于这一行:
((ScrollViewer)obj).ChangeView(0.0f, ((ScrollViewer)obj).ExtentHeight, 1.0f, true);
我还将方法与事件处理程序分开,因为每次文本更改时我都不想滚动。
答案 1 :(得分:2)
如果有人需要滚动到UWP应用中TextBox的底部:
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;
}
}
}
其中textBox1是要滚动到底部的TextBox。
答案 2 :(得分:0)
等效于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;
}
}
其中responseText为TextBox^ responseText
,即您要滚动的TextBox(可能与发件人相同)。