C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Syntax: Please look at the syntax of the DisplayMemberBinding attributes. The Name, ID and Size are properties on the Animal class.
Note: ListView is really a container for other controls. This example is mostly about using GridView—but that too is useful.
Example markup: XAML
<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>
Example code: C#
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 });
}
}
}
So: Where "Binding Name" is specified, the Name string is displayed in that row's cell.
And: In this way, we populate each of the three cells of the GridView within the ListView. We operate mostly on the GridView.
Tip: In data binding, properties are best. Often developers will try using fields, but these are not usually recognized.