谢谢你, 布拉希姆
答案 0 :(得分:1)
这是测试XAML:
<ScrollViewer x:Name="scrollViewer">
<StackPanel x:Name="stackPanel"
Orientation="Vertical">
<TextBox Width="100"
Text="#1"
GotFocus="TextBox_GotFocus" />
<Rectangle Fill="AliceBlue"
Width="100"
Height="400" />
<TextBox Width="100"
Text="#2"
GotFocus="TextBox_GotFocus" />
<Rectangle Fill="AliceBlue"
Width="100"
Height="400" />
<TextBox Width="100"
Text="#3"
GotFocus="TextBox_GotFocus" />
</StackPanel>
</ScrollViewer>
'TextBox_GotFocus'事件的代码:
private void TextBox_GotFocus(object sender, RoutedEventArgs e)
{
GeneralTransform gt = ((TextBox)sender).TransformToVisual(this);
Point textBoxPositionRelativeToControl = gt.Transform(new Point(0, 0));
if (textBoxPositionRelativeToControl.Y > this.ActualHeight
|| textBoxPositionRelativeToControl.Y < this.ActualHeight)
{
gt = ((TextBox)sender).TransformToVisual(stackPanel);
Point textBoxPositionRelativeToStackPanel = gt.Transform(new Point(0, 0));
scrollViewer.ScrollToVerticalOffset(textBoxPositionRelativeToStackPanel.Y - this.ActualHeight / 2);
}
}
更新了代码,以便在文本框位于可见区域之外时,滚动查看器将隐藏文本框居中;否则,没有任何反应。如果您切换到下一个或上一个文本框(shift + tab),则可以正常工作。