WPF: Using an instance name for the listview

Similar to the listbox, we can give an instance to the ListView. Note that this is different from the previous example where we have used ObservableCollection.

In using ObservableCollection, items are added and the XAML view will be updated immediately as the View will be notify of the new items in the collection.

MainWindow.xaml
<Window x:Class="ListViewNSpace.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:src="clr-namespace:ListViewNSpace"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <ListView Name="lv">
            <ListView.View>
                <GridView AllowsColumnReorder="true" ColumnHeaderToolTip="Employee Information">
                    <GridViewColumn DisplayMemberBinding="{Binding FirstName}" Header="First Name" Width="100"/>
                    <GridViewColumn DisplayMemberBinding="{Binding LastName}" Header="Last Name" Width="100"/>
                    <GridViewColumn DisplayMemberBinding="{Binding EmployeeNumber}" Header="Employee No." Width="100"/>
                </GridView>
            </ListView.View>
        </ListView>
    </Grid>
</Window>

MainWindow.xaml.cs
using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Documents;

namespace ListViewNSpace
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>

    public partial class MainWindow : Window
    {

        public class Employee
        {
            public String FirstName { get; set; }
            public String LastName { get; set; }
            public int EmployeeNumber { get; set; }

            public Employee(String firstName, String lastName, int employeeNumber)
            {
                this.FirstName = firstName;
                this.LastName = lastName;
                this.EmployeeNumber = employeeNumber;
            }
        }

        public MainWindow()
        {
            InitializeComponent();

            List<Employee> cust = new List<Employee>();

            cust.Add(new Employee("Michael", "Anderberg", 1812));
            cust.Add(new Employee("Chris", "Ashton", 2356));
            cust.Add(new Employee("Cassie", "Hicks", 1211));
            cust.Add(new Employee("Guido", "Pi", 1900));

            lv.ItemsSource = cust;

        }
    }
}

listviewspace

 

 

Series Navigation<< WPF: Listview with a gridview
WPF: Populating a datagrid using a collection >>