如何使Silverlight ScrollViewer滚动以显示具有焦点的子控件?

Cra*_*rer 13 silverlight scrollviewer

我有一个ScrollViewer,其中包含一个包含多个控件的Grid.用户可以通过控件进行制表,但最终它们会切换到不在视图中的控件 - 因此他们必须进行手动滚动以使控件再次可见.

有没有办法让ScrollViewer自动滚动,以便始终可以看到聚焦控件.如果失败了,有没有什么方法可以让这个工作,除了在每个控件上听一个GotFocus事件,然后滚动ScrollViewer使控件可见?

目前我正在使用Silverlight 2.

Kir*_*oev 12

我使用Silverlight 3进行了测试.我不确定SL2.

这是我的XAML:

<ScrollViewer Height="200" Width="200" KeyUp="ScrollViewer_KeyUp">
    <StackPanel>
        <Button Content="1" Height="20" />
        <Button Content="2" Height="20" />
        <Button Content="3" Height="20" />
        <Button Content="4" Height="20" />
        <Button Content="5" Height="20" />
        <Button Content="6" Height="20" />
        <Button Content="7" Height="20" />
        <Button Content="8" Height="20" />
        <Button Content="9" Height="20" />
    <Button Content="10" Height="20" />
        <Button Content="11" Height="20" />
        <Button Content="12" Height="20" />
        <Button Content="13" Height="20" />
        <Button Content="14" Height="20" />
        <Button Content="15" Height="20" />
        <Button Content="16" Height="20" />
        <Button Content="17" Height="20" />
        <Button Content="18" Height="20" />
        <Button Content="19" Height="20" />
        <Button Content="20" Height="20" />
    </StackPanel>
</ScrollViewer>
Run Code Online (Sandbox Code Playgroud)

这是代码隐藏的代码:

private void ScrollViewer_KeyUp(object sender, KeyEventArgs e)
{
    ScrollViewer scrollViewer = sender as ScrollViewer;
    FrameworkElement focusedElement = FocusManager.GetFocusedElement() as FrameworkElement;
    GeneralTransform focusedVisualTransform = focusedElement.TransformToVisual(scrollViewer);
    Rect rectangle = focusedVisualTransform.TransformBounds(new Rect(new Point(focusedElement.Margin.Left, focusedElement.Margin.Top), focusedElement.RenderSize));
    double newOffset = scrollViewer.VerticalOffset + (rectangle.Bottom - scrollViewer.ViewportHeight);
    scrollViewer.ScrollToVerticalOffset(newOffset);
}
Run Code Online (Sandbox Code Playgroud)

我做的是单击按钮#1和选项卡,直到我到达按钮#20.它对我有用.试一试,让我知道它对你有用.


olo*_*rin 11

silverlight工具包包含一个方法"ScrollIntoView".

添加对System.Windows.Controls.Toolkit.dll的引用,您应该能够使用下面的代码.

scrollViewer.ScrollIntoView(control);