如何确定键盘偏移 [英] How to determine the keyboard offset

查看:21
本文介绍了如何确定键盘偏移的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我昨天遇到了这个问题,过去似乎很多人都遇到过类似的问题,所以我想我会提出我的问题 &我最终想出的解决方案.微软在 8.1 SDK 中有更简洁的解决方案,但绝大多数 WP 应用用户使用的是 8.0 及更低版本,所以我想这仍然会有所帮助.

I had this issue yesterday and it seems a lot of people have had similar issues in the past, so I figured I would pose my question & the solution I ended up coming up with. Microsoft has cleaner solutions to this in the 8.1 SDK, but the vast majority of WP app users are on 8.0 and below, so I imagine this will still be helpful.

当您在 Windows Phone 7/8 Silverlight 应用程序中打开虚拟键盘,并且导致键盘打开的文本框位于屏幕的下半部分(会被键盘覆盖)时,它会滚动整页向上.如果顶部有您需要显示的内容,您如何确定它滚动了多少?

When you open the virtual keyboard in a Windows Phone 7/8 Silverlight app, and the text box that caused the keyboard to open is on the lower half of the screen (that would be covered by the keyboard), it scrolls the entire page up. How can you determine how much it has scrolled, in case there was content at the top that you need displayed?

推荐答案

有点笨拙,但是您可以通过查看根框架的偏移量来获得页面向上滚动的量.

It's a little clunky, but you can get the amount the page was scrolled up by looking at the offset of the root frame.

由于这是动画到位,问题变成了何时".我发现有效的是,当文本框的 GotFocused 事件被触发时,订阅 LayoutUpdated 事件,当 LayoutUpdated 被触发时,从那里获取偏移量.如果您尚未订阅该事件,则可以在 LostFocus 事件中取消订阅.这样当它移动时,你就会得到改变.

Since this is animated into position, the question becomes "when". What I found that works is, when a text box's GotFocused event is fired, subscribe to the LayoutUpdated event, and when LayoutUpdated is fired, grab the offset from there. If you weren't already subscribed to that event, you can unsubscribe in the LostFocus event. That way as it moves, you'll get the change.

double lastOffset = 0;

private void TextBox_GotFocus(object sender, RoutedEventArgs e)
{
    LayoutUpdated += MyControl_LayoutUpdated;
}

private void MyControl_LayoutUpdated(object sender, EventArgs e)
{
    // Grab the offset out of the root frame's RenderTransform object
    PhoneApplicationFrame root = App.Current.RootVisual as PhoneApplicationFrame;
    TransformGroup transform = root.RenderTransform as TransformGroup;
    double offset = transform.Value.OffsetY;

    if (offset != lastOffset)
    {
        // Do your logic here if the offset has changed
        lastOffset = offset;
    }
}

private void TextBox_LostFocus(object sender, RoutedEventArgs e)
{
   // Unsubcribe to updates and reset the offset to 0
   LayoutUpdated -= MyControl_LayoutUpdated;
   lastOffset = 0;
}

获得此偏移后,您可以根据需要更改控件.您可以将控件的高度缩小该数量,或者如果顶部有一些小东西,例如标题,您可以通过偏移量的倒数应用 TranslateTransform 将其向下移动.

After you have this offset, you can alter your controls as needed. You can either shrink the height of a control by that amount, or if you have something small at the top, like a header, you can apply a TranslateTransform by the inverse of the offset to just move it downward.

这篇关于如何确定键盘偏移的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆