[UWP][XAML]How to create a ListView that has a TextBox just below the last ListViewItem

Would you like to create a list of items in your UWP and allow your users to quickly create a new item by making the last item in the list an input field like a TextBox? Have you tried creating the layout for this but did not get it 100% right? After reading this, you know how to set this up in XAML while preserving ListView virtualization

Since I’ve been working on Wunderlist for Windows we changed the position of the Task Input Field from the bottom of the screen to the bottom of the list a few times. And every time we want to “stick” or “glue” it at the end of the ListView, we ask ourselves what layout used in the past in order to do this while preserving ListView virtualization.

Input field just below the last item of ListView

The solution we are going to use here is not to add a DataTemplate with an input field but to use a layout that accepts a ListView and TextBox and make them appear vertically stacked. The goal is:

It looks like this:

listview

Create the layout panel

The trick here is to use a Grid with VerticalAlignment="Top". The ListView goes into a star sized row and the TextBox into an Auto sized row.

<Grid VerticalAlignment="Top">
    <Grid.RowDefinitions>
        <RowDefinition Height="*"/>
        <RowDefinition Height="Auto"/>
    </Grid.RowDefinitions>
    <ListView x:Name="ListViewTest">
        <ListView.ItemTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding}"/>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
    <TextBox 
        x:Name="TextBoxAdd" 
        FontSize="48" 
        TextWrapping="Wrap" 
        MaxHeight="300" 
        Grid.Row="1" 
        KeyDown="TextBox_KeyDown"/>
</Grid>
private void TextBox_KeyDown(object sender, KeyRoutedEventArgs e)
{
    if (e.Key == Windows.System.VirtualKey.Enter)
    {
        e.Handled = true;
        ListViewTest.Items.Add(TextBoxAdd.Text);
        TextBoxAdd.Text = "";
    }
}

Remember that the Grid (<Grid VerticalAlignment="Top">) can itself be a child of another Grid. But One thing you cannot do is make the ListView or one of its direct parents a child of a StackPanel. That would break virtualization.

To check if virtualization is still working, run a UI Analyses.