#828 – ListView and GridView Data Binding Example

ListView control contains a collection of items that you can view in different ways.  The current view can be set using the View property, which can be set to an instance of a GridView.  A GridView is an object that can display the data in columns.

Below is a complete example of a bound ListView that uses a GridView to display its items.  The ListView is bound to a collection and the GridView contains GridViewColumn instances, each of which is bound to a property of the items contained in the collection.

    <StackPanel>
        <Label Content="Ad eundum quo nemo ante iit"
               Margin="5"
               Background="LightCoral"/>
        <ListView ItemsSource="{Binding Guys}">
            <ListView.View>
                <GridView>
                    <GridViewColumn DisplayMemberBinding="{Binding Name}"
                                    Header="Guy"/>
                    <GridViewColumn DisplayMemberBinding="{Binding Age}"
                                    Header="Age"/>
                </GridView>
            </ListView.View>
        </ListView>
    </StackPanel>

The code-behind for the top-level Window sets the data context and creates the collection.

    public partial class MainWindow : Window, INotifyPropertyChanged
    {
        public ObservableCollection<Person> Guys { get; protected set; }

        public MainWindow()
        {
            this.InitializeComponent();
            this.DataContext = this;

            Guys = new ObservableCollection<Person>();
            Guys.Add(new Person("Julius Caesar", 40));
            Guys.Add(new Person("Pompeius Magnus", 46));
            Guys.Add(new Person("Marcus Crassus", 55));
            RaisePropertyChanged("Guys");
        }

        public event PropertyChangedEventHandler PropertyChanged = delegate { };

        private void RaisePropertyChanged(string propName)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propName));
        }
    }

For completeness, here is the implementation of the Person class.

    public class Person :  INotifyPropertyChanged
    {
        public string Name { get; set; }
        public int Age { get; set; }

        public Person(string name, int age)
        {
            Name = name;
            Age = age;
        }

        public event PropertyChangedEventHandler PropertyChanged;

        private void RaisePropertyChanged(string propName)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propName));
        }
    }

828-001

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

2 Responses to #828 – ListView and GridView Data Binding Example

  1. Pingback: Dew Drop – May 28, 2013 (#1,555) | Alvin Ashcraft's Morning Dew

  2. Sam says:

    Thanks, Bro

Leave a comment