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.
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:
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.