ListView
A ListView
displays data. By default it contains a GridView
. It can display data in different ways—it is a container for other controls like GridView
.
ListView
is really a container for other controls. This example is mostly about using GridView
—but that too is useful.
This example uses a GridView
with 3 GridViewColumns
nested within it. A Name (AnimalList
) is defined on the ListView
element. On each GridViewColumn
, we specify a DisplayMemberBinding
.
DisplayMemberBinding
attributes. The Name, ID and Size
are properties on the Animal class
.<Window x:Class="WpfApplication2.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="ListView" Height="350" Width="525" Loaded="Window_Loaded"> <Grid> <ListView HorizontalAlignment="Left" Height="299" Margin="10,10,0,0" VerticalAlignment="Top" Width="497" Name="AnimalList"> <ListView.View> <GridView> <GridViewColumn Header="Name" DisplayMemberBinding="{Binding Name}" Width="100"/> <GridViewColumn Header="ID" DisplayMemberBinding="{Binding ID}" Width="100"/> <GridViewColumn Header="Size" DisplayMemberBinding="{Binding Size}" Width="100"/> </GridView> </ListView.View> </ListView> </Grid> </Window>using System.Windows; class Animal { public string Name { get; set; } public string ID { get; set; } public int Size { get; set; } } namespace WpfApplication2 { public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void Window_Loaded(object sender, RoutedEventArgs e) { AnimalList.Items.Add(new Animal() { Name = "Cat", ID = "123A", Size = 100 }); AnimalList.Items.Add(new Animal() { Name = "Dog", ID = "456X", Size = 200 }); AnimalList.Items.Add(new Animal() { Name = "Rabbit", ID = "333E", Size = 40 }); } } }
In the Window_Loaded
event, we access the AnimalList
by its name. We add Animal objects to its Items collection with the Add method.
Size
) match the bindings specified in the GridView
.string
is displayed in that row's cell.GridView
within the ListView
. We operate mostly on the GridView
.DisplayMemberBinding
When creating this example, the most confusing part was using the DisplayMemberBinding
. The curly brackets within the attribute are required: these are part of the XAML.
A ListView
is largely a container for other controls. For most programs, consider instead a DataGrid
or a GridView
without a ListView
.