虚拟键盘打开时以编程方式将控件滚动到视图中

Dam*_*Arh 3 windows-8 windows-runtime winrt-xaml

我有一个页面,其中包含一组垂直文本框.如果其中一个是聚焦的,即使显示屏幕键盘,所有这些都应该是可见的.只有足够的它们都适合键盘上方的可用空间.当底部文本框被聚焦时,页面会自动向上滚动,以便所有页面都可见,但如果顶部文本框被聚焦,则屏幕键盘覆盖底部文本框.

这是我的页面的简化示例:

<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
    <ItemsControl ItemsSource="{Binding List}" Margin="120 140 0 0">
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Horizontal" Margin="0 10 0 0">
                    <TextBox Text="{Binding Text, Mode=TwoWay}" />
                </StackPanel>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>
</Grid>
Run Code Online (Sandbox Code Playgroud)

DataContext 包含10个项目的列表:

public class Item
{
    public string Text { get; set; }
}

public class ViewModel
{
    public List<Item> List { get; set; }
}

public MainPage()
{
    this.InitializeComponent();
    DataContext = new ViewModel
    {
        List = Enumerable.Range(0, 10).Select(i => new Item { Text = i.ToString() }).ToList()
    };
}
Run Code Online (Sandbox Code Playgroud)

我已经尝试过几种方法,但都没有成功:

  1. TextBox.GotFocus事件中以编程方式将焦点更改为底部文本框并返回.
  2. TextBox.GotFocus事件和InputPane.Showing事件中尝试设置a的垂直偏移ScrollViewer:(a)我在页面中包含的那个Grid(b)在PageWindows 上面的可视树中用于自动将聚焦控件放在视图中的那个.在这两种情况下,ScrollViewer都不会对ScrollToVerticalOffset通话做出反应.

我也查看了这个问题中提出的示例,但它对屏幕键盘的反应不同,而不是通过滚动页面.

Dam*_*Arh 8

感谢Cyprient的回答,我终于设法让它工作了.我从我的问题中追求选项2.a.

UpdateLayout()需要添加调用,但是当我将它放在GotFocus事件处理程序中时,它只在虚拟键盘已经打开后才能工作.为了让键盘第一次打开时,我不得不进行两项更改:

  1. 我不得不把代码中Showing的事件InputPane.
  2. 我不得不把它放在调度程序的回调中,以便只在Showing事件处理程序返回后调用它.

这是最终的代码:

public MainPage()
{
    this.InitializeComponent();
    DataContext = new ViewModel
    {
        List = Enumerable.Range(0, 10).Select(i => new Item { Text = i.ToString() }).ToList()
    };

    var inputPane = InputPane.GetForCurrentView();
    inputPane.Showing += InputPane_Showing;
}

private async void InputPane_Showing(InputPane sender, InputPaneVisibilityEventArgs args)
{
    await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
        {
            var parentScrollViewer = FindParent<ScrollViewer>(this.pageRoot);
            parentScrollViewer.VerticalScrollMode = ScrollMode.Enabled;
            parentScrollViewer.ScrollToVerticalOffset(65);
            parentScrollViewer.UpdateLayout();
        });
}
Run Code Online (Sandbox Code Playgroud)

这是我正在使用的辅助函数来获取对ScrollViewer页面内容自动滚动时使用的辅助函数,因为聚焦控件不会以其他方式显示:

public static T FindParent<T>(FrameworkElement reference)
    where T : FrameworkElement
{
    FrameworkElement parent = reference;
    while (parent != null)
    {
        parent = parent.Parent as FrameworkElement;

        var rc = parent as T;
        if (rc != null)
        {
            return rc;
        }
    }

    return null;
}
Run Code Online (Sandbox Code Playgroud)