How to determine the keyboard offset

前端 未结 1 741
刺人心
刺人心 2021-01-29 07:06

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.

相关标签:
1条回答
  • 2021-01-29 07:26

    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.

    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;
    }
    

    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.

    0 讨论(0)
提交回复
热议问题