How To Make A Simple Grid In WPF


Well, there are a lot of paths that you can take if you want to create a grid in WPF. However, I’ll show the most simple (at least for me).

 

Definitely the ListView is one of the most powerful (maybe the number one) controls in WPF so we can create a simple grid easily using this control. Now we need a source of data and we’re going to use an ObservableCollection, the msdn description of this class is the following:

 

“Represents a dynamic data collection that provides notifications when items get added, removed, or when the whole list is refreshed.“

 

So as you can realize this blows away a lot of painful things to do because we can do what we want with our collection and the framework updates the layout automatically.

 

This is the XAML:

<Window x:Class=”BlogStuff.Window1″

xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation”

xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml”

Title=”My Simple Grid” Height=”300″ Width=”300″>

<ListView ItemsSource=”{Binding}”>

<ListView.View>

<GridView>

<GridViewColumn Header=”Name” DisplayMemberBinding=”{Binding Path=Name}”>

<GridViewColumn.CellTemplate>

<DataTemplate>

<Label/>

</DataTemplate>

</GridViewColumn.CellTemplate>

</GridViewColumn>

<GridViewColumn Header=”Age” DisplayMemberBinding=”{Binding Path=Age}”>

<GridViewColumn.CellTemplate>

<DataTemplate>

<Label/>

</DataTemplate>

</GridViewColumn.CellTemplate>

</GridViewColumn>

<GridViewColumn Header=”Random Number” DisplayMemberBinding=”{Binding Path=RandomNumber}”>

<GridViewColumn.CellTemplate>

<DataTemplate>

<Label/>

</DataTemplate>

</GridViewColumn.CellTemplate>

</GridViewColumn>

</GridView>

</ListView.View>

</ListView>

</Window>

When you create the ListView you should set the ItemsSource property to {Binding}, this way the items will be taken from the DataContext property of the ListView, in this case the DataContext is the ObservableCollection.

 

Inside the GridView you can create the columns, then you can set which property of the item will be displayed in the current column with the DisplayMemberBinding property. Remember that the items are the items from the collection. Also you can define a DataTemplate for the cells, so if you want to show your info in buttons instead of labels you can change them easily without changing the code behind.

 

This is the Code Behind (C#):

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Data;

using System.Windows.Documents;

using System.Windows.Input;

using System.Windows.Media;

using System.Windows.Media.Imaging;

using System.Windows.Navigation;

using System.Windows.Shapes;

 

//ObservableCollection namespace:

using System.Collections.ObjectModel;

 

namespace BlogStuff

{

///

/// Interaction logic for Window1.xaml

///

public partial class Window1 : Window

{

ObservableCollection<Guest> guests = new ObservableCollection<Guest>();

Random gen = new Random(DateTime.Now.Millisecond);

 

public Window1()

{

InitializeComponent();

this.DataContext = guests;

 

guests.Add(new Guest()

{

Name = “Fernando Romero”,

Age = 23,

RandomNumber = gen.Next(100)

});

 

guests.Add(new Guest()

{

Name = “Luis Del Vasto”,

Age = 22,

RandomNumber = gen.Next(100)

});

 

guests.Add(new Guest()

{

Name = “Nestor Martinez”,

Age = 26,

RandomNumber = gen.Next(100)

});

}

}

 

public class Guest

{

public string Name { get; set; }

public int Age { get; set; }

public int RandomNumber { get; set; }

}

}

 

Just after the first line of code in the constructor we set the DataContext property (of the window) with the guests collection, maybe you are thinking: “but the collection should be the DataContext of the ListView”, well that’s exactly what it is, In WPF the DataContext property is passed to the children by default, so as long as the ListView is contained by the window, then it will inherit this property. However, if you set the DataContext property of the ListView to other object then it will be overwritten.


I hope this could be useful for all of you guys.

Best,
FeR

4 Comments

  1. Daveg said,

    September 17, 2008 at 5:37 pm

    What if I have more than one ListView in the window? Is there a way to associate each individual ListView to a Collection?

  2. fernandojhoel said,

    September 18, 2008 at 1:34 pm

    In this case we are setting the collection as the datacontext for the whole window, this means that every visual child of the window (including your listviews) will bind to this collection if you set the ItemsSource property (ItemsSource=”{Binding}”).

    And not just a ListView. In my projects almost always I work with a core collection with all of the data that I need and then I bind this data to a lot of controls. The point is that you can have the same source for multiple UI elements.

    Good luck and thanks for comment.

  3. Daveg said,

    September 19, 2008 at 7:31 pm

    I worked it out. I recognize that my case is quite a bit different from your example, but it was your posting here that got me over a hump that had perplexed me for days. Thanks very much for that!

    What I ended up having to do in my application is assign a datacontext for each ListView in my application. I see your point that I could simply create a source for all of the controls in the application and they would only use the elements that are intended for them, which is a viable alternative. But I found it easier (read: more maintainable in the long term as this will eventually be a large application) to separate them and assign the DataContexts to the appropriate controls. To use one massive collection would be difficult to maintain. That said, I think there are some cases where a large collection could support a small-ish collection of controls in order to maintain a logical binding between them.

    Again, thank you very much for getting me started! I was completely stuck on how to use the WPF ListViews until I came across your blog.

  4. maninder said,

    February 12, 2009 at 9:06 am

    amazing man i found the solution of my porblem
    thanks
    from maninder


Post a Comment