UWP開發入門(二十)——鍵盤彈起時變動界面佈局

  UWP APP在鍵盤彈起或隱藏時,並不會自動處理界面佈局。有時會出現鍵盤遮擋了下一個須要填寫的文本框,或是下一步按鈕的狀況。本篇咱們以登陸界面作例子,用一種巧妙簡單的方式在鍵盤彈起和隱藏時更改界面的佈局。git

  首先咱們建立一個登陸界面,很簡單的畫了兩個TextBlock,一個TextBox和一個PasswordBox,同時在下方放置來一個Button用來點擊登陸。github

    <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*"></ColumnDefinition>
            <ColumnDefinition Width="Auto"></ColumnDefinition>
            <ColumnDefinition Width="2*"></ColumnDefinition>
            <ColumnDefinition Width="*"></ColumnDefinition>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="2*"></RowDefinition>
            <RowDefinition Height="Auto"></RowDefinition>
            <RowDefinition Height="Auto"></RowDefinition>
            <RowDefinition Height="*"></RowDefinition>
            <RowDefinition x:Name="rowBottom" Height="*"></RowDefinition>
        </Grid.RowDefinitions>

        <TextBlock Grid.Column="1" Grid.Row="1">用戶名</TextBlock>
        <TextBlock Grid.Column="1" Grid.Row="2">密碼</TextBlock>
        <TextBox Grid.Column="2" Grid.Row="1"></TextBox>
        <PasswordBox Grid.Column="2" Grid.Row="2"></PasswordBox>

        <Button Grid.Column="1" Grid.ColumnSpan="2" Grid.Row="3" HorizontalAlignment="Stretch">登陸</Button>
    </Grid>

  

  能夠注意到咱們給最下面的RowDefinition設置了x:Name屬性,一般不會在代碼中操做的UIElement是不須要也不該該設置x:Name的(存在影響性能和內存泄漏的可能,且使用MVVM的話也不須要ViewModel中操做UIElement)。佈局

  看到這裏能夠推測出咱們是經過修改rowBottomHeight屬性,將該Row以上的頁面內容頂起,形成頁面向上推進的視覺效果。性能

    public sealed partial class MainPage : Page
    {
        public MainPage()
        {
            this.InitializeComponent();
            InputPane.GetForCurrentView().Showing += MainPage_Showing;
            InputPane.GetForCurrentView().Hiding += MainPage_Hiding;
        }

        private void MainPage_Hiding(InputPane sender, InputPaneVisibilityEventArgs args)
        {
            this.rowBottom.Height = new GridLength(1, GridUnitType.Star);
        }

        private void MainPage_Showing(InputPane sender, InputPaneVisibilityEventArgs args)
        {
            this.rowBottom.Height = new GridLength(args.OccludedRect.Height);
        }
    }

  頁面的代碼部分咱們能夠看到,經過InputPane.GetForCurrentView()方法監聽鍵盤的ShowingHiding事件。同時在Showing事件的響應方法中,將rowBottomHeight屬性設置爲鍵盤的實際高度,以保持rowBottom以上的內容可見。而在Hiding事件中,則將rowBottomHeight屬性還原,已達到在鍵盤隱藏時還原佈局的目的。this

  本篇的內容是否是有些過於簡單了?實際上這個操做RowDefinition高度的小技巧能夠延伸出許多有意思的用法。好比聊天窗口彈出的表情區域,就能夠如法炮製隱藏在鍵盤的下面。同理ColumDefinition經過隱藏和顯示,能夠結合SplitView作出多個層次摺疊的APP,再配合一下SizeChanged事件,想一想就有點頭疼,千萬不能讓UE她們知道……spa

  GitHubcode

  https://github.com/manupstairs/UWPSamples/tree/master/UWPSamples/UpdateLayoutWhenKeyboardPopupblog

相關文章
相關標籤/搜索