Home  separator  Layout  separator  Grid Panel
Bookmark and Share Share...    Subscribe to this feed Feed   About Christian Moser  


Grid Panel

Introduction

How to define rows and columns

How to add controls to the grid

Resize columns or rows

How to share the width of a column over multiple grids

Using GridLenghts from code

Introduction

The grid is a layout panel that arranges its child controls in a tabular structure of rows and columns. Its functionality is similar to the HTML table but more flexible. A cell can contain multiple controls, they can span over multiple cells and even overlap themselves.

The resize behaviour of the controls is defined by the HorizontalAlignment and VerticalAlignment properties who define the anchors. The distance between the anchor and the grid line is specified by the margin of the control

Define Rows and Columns

The grid has one row and column by default. To create additional rows and columns, you have to add RowDefinition items to the RowDefinitions collection and ColumnDefinition items to the ColumnDefinitions collection. The following example shows a grid with three rows and two columns.

The size can be specified as an absolute amount of logical units, as a percentage value or automatically.

Fixed Fixed size of logical units (1/96 inch)
Auto Takes as much space as needed by the contained control
Star (*) Takes as much space as available (after filling all auto and fixed sized columns), proportionally divided over all star-sized columns. So 3*/5* means the same as 30*/50*. Remember that star-sizing does not work if the grid size is calculated based on its content.
 
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" />
        <RowDefinition Height="Auto" />
        <RowDefinition Height="*" />
        <RowDefinition Height="28" />
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="Auto" />
        <ColumnDefinition Width="200" />
    </Grid.ColumnDefinitions>
</Grid>
 
 

How to add controls to the grid

To add controls to the grid layout panel just put the declaration between the opening and closing tags of the Grid. Keep in mind that the row- and columndefinitions must precced any definition of child controls.

The grid layout panel provides the two attached properties Grid.Column and Grid.Row to define the location of the control.

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" />
        <RowDefinition Height="Auto" />
        <RowDefinition Height="*" />
        <RowDefinition Height="28" />
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="Auto" />
        <ColumnDefinition Width="200" />
    </Grid.ColumnDefinitions>
    <Label Grid.Row="0" Grid.Column="0" Content="Name:"/>
    <Label Grid.Row="1" Grid.Column="0" Content="E-Mail:"/>
    <Label Grid.Row="2" Grid.Column="0" Content="Comment:"/>
    <TextBox Grid.Column="1" Grid.Row="0" Margin="3" />
    <TextBox Grid.Column="1" Grid.Row="1" Margin="3" />
    <TextBox Grid.Column="1" Grid.Row="2" Margin="3" />
    <Button Grid.Column="1" Grid.Row="3" HorizontalAlignment="Right" 
            MinWidth="80" Margin="3" Content="Send"  />
</Grid>
 

Resizable columns or rows

WPF provides a control called the GridSplitter. This control is added like any other control to a cell of the grid. The special thing is that is grabs itself the nearest gridline to change its width or height when you drag this control around.

<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*"/>
        <ColumnDefinition Width="Auto"/>
        <ColumnDefinition Width="*"/>
    </Grid.ColumnDefinitions>
    <Label Content="Left" Grid.Column="0" />
    <GridSplitter HorizontalAlignment="Right" 
                  VerticalAlignment="Stretch" 
                  Grid.Column="1" ResizeBehavior="PreviousAndNext"
                  Width="5" Background="#FFBCBCBC"/>
    <Label Content="Right" Grid.Column="2" />
</Grid>
 

The best way to align a grid splitter is to place it in its own auto-sized column. Doing it this way prevents overlapping to adjacent cells. To ensure that the grid splitter changes the size of the previous and next cell you have to set the ResizeBehavior to PreviousAndNext.

The splitter normally recognizes the resize direction according to the ratio between its height and width. But if you like you can also manually set the ResizeDirection to Columns or Rows.

<GridSplitter ResizeDirection="Columns"/>
 

How to share the width of a column over multiple grids

The shared size feature of the grid layout allows it to synchronize the width of columns over multiple grids. The feature is very useful if you want to realize a multi-column listview by using a grid as layout panel within the data template. Because each item contains its own grid, the columns will not have the same width.

By setting the attached property Grid.IsSharedSizeScope to true on a parent element you define a scope within the column-widths are shared.

To synchronize the width of two columndefinitions, set the SharedSizeGroup to the same name.

 
<ItemsControl Grid.IsSharedSizeScope="True" >
  <ItemsControl.ItemTemplate> 
    <DataTemplate>
      <Grid>
        <Grid.ColumnDefinitions>
          <ColumnDefinition SharedSizeGroup="FirstColumn" Width="Auto"/>
          <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>
        <TextBlock Text="{Binding Path=Key}" TextWrapping="Wrap"/>
        <TextBlock Text="{Binding Path=Value}" Grid.Column="1" TextWrapping="Wrap"/>
      </Grid>
    </DataTemplate>
  </ItemsControl.ItemTemplate>
</ItemsControl>
 
 

Useful Hints

Columns and rows that participate in size-sharing do not respect Star sizing. In the size-sharing scenario, Star sizing is treated as Auto. Since TextWrapping on TextBlocks within an SharedSize column does not work you can exclude your last column from the shared size. This often helps to resolve the problem.

Using GridLenghts from code

If you want to add columns or rows by code, you can use the GridLength class to define the differenz types of sizes.


Auto sized GridLength.Auto
Star sized new GridLength(1,GridUnitType.Star)
Fixed size new GridLength(100,GridUnitType.Pixel)
Grid grid = new Grid();
 
ColumnDefinition col1 = new ColumnDefinition();
col1.Width = GridLength.Auto;
ColumnDefinition col2 = new ColumnDefinition();
col2.Width = new GridLength(1,GridUnitType.Star);
 
grid.ColumnDefinitions.Add(col1);
grid.ColumnDefinitions.Add(col2);
 

More on this topic

How to create a resizable column



Last modified: 2011-10-03 09:22:29
Copyright (c) by Christian Moser, 2011.

 Comments on this article

Show all comments
Dhananjay kumar
Commented on 16.December 2008
It is really a nice article
David
Commented on 19.December 2008
Is the last specified button supposed to be labeled Row:3 Col:2? I am just now learning WPF and like what I see. Thanks for the information and articles. Keep up the good work.
yukA
Commented on 6.January 2009
@David
I was wondering the same and, in fact, there is a little mistake in the code. You are actually right that the row should be set to 3 and the column should be set to 2.
Has a little hint, when the column index is coded out of range, the designer selects the last valid index available in the table. Thus 2 in this example even if the property is set to 4 or more.
Anyways, nice website except that the spam protection seems not to work properly...
venugopal volla
Commented on 12.May 2009
Hey, Iam just now learning WPF and its really a cool article.
Good one to start with...;)
vivekanandhan
Commented on 20.May 2009
It's really a nice article.I am very impressed with designs.it's really useful for beginners.Keep up the good work.
baljeet
Commented on 28.May 2009
can u please elaborate one more detail that is how to add control to particular grid cell and row from code??
jeevan mummadi
Commented on 28.May 2009
very nice article.
tell me how to set border property for grid ?
Christian Moser
Commented on 28.May 2009
Hi Jeevan,
the grid control does not have a Border property. Only a background brush can be set. You need to wrap your grid in a border control.
Ashka Modi
Commented on 1.June 2009
Hey its good article. can we bind grid like usual grid in web application? can't u add some binding example which runtime creates rows and columns direct from DB?
Ashka Modi
Commented on 1.June 2009
Hey its good article. can we bind grid like usual grid in web application? can't u add some binding example which runtime creates rows and columns direct from DB?
nandini
Commented on 8.June 2009
Hi..Really it is nice articel for beginners..
daya
Commented on 11.June 2009
Good one.
Srujana
Commented on 16.June 2009
The complete WPF article is up to the point and really very helpful especially for the beginners.
hari
Commented on 23.June 2009
Hi,
I was trying this in code and noticed that though first we need to add the row definitions and column definitions but the definition of child controls can be done only above the row definitions and not below the row and column definitions.
I am using Visual C#2008 Express.
Deepa
Commented on 26.June 2009
Hi Its really Nice article,
can u explain me how to drop element in cell.

i will be thank full on ur support
Farooq Azam
Commented on 20.July 2009
Thanks a lot!

This is was very helpful.

Keep up the great work.
Jogender...
Commented on 3.August 2009
Good one. Everything is nice, clear and helpful too.
Thanks a lot.

Prashant
Commented on 16.September 2009
Hi,Iam just now started learning WPF and its good one & It's really a nice article.I am very impressed with designs.it's really useful for beginners.
ME
Commented on 7.October 2009
HEROIN!
Vijay
Commented on 25.November 2009
Superb nice tutorial:)

http://mindiansprts.blogspot.com
Vijay
Commented on 25.November 2009
Superb nice tutorial:)
http://mindiansports.blogspot.com

Sathya
Commented on 5.December 2009
Thanks, very nice
Anonymous
Commented on 7.December 2009
You are an absolute legend! Everything was so well explained, it all makes sense now.Thank You so much.

Keep up the great work.
ap
Commented on 7.December 2009
Nice job!

Is this article dereferred?
'How to create a resizable column'
--> Article not found!
Rave
Commented on 17.December 2009
Nice Article ,really helpful for those who new to wpf
Kartik
Commented on 5.January 2010
Is there any way to get height of grid, created dynamically at run time? Initially i am not set height of grid, but at run time as content are added in grid, i want to height of grid.
umesh
Commented on 12.January 2010
nice article. Thanks a lot for your contribution.
Piyush Goriya
Commented on 26.January 2010
Nice Article really helpful for those who new to wpf with controls
Prem
Commented on 26.January 2010
Very good for beginners
@shish
Commented on 8.February 2010
How to create dynamic rows and columns (i.e I want to create same #s of rows what I am getting from my SQL).
BTW- u'r notes, examples r v.good for beginners.
Ashok Zenerica
Commented on 9.March 2010
savvy tutorials
Abirami
Commented on 11.March 2010
Hi @shish,
this grid is different from the grid what u r thinking..
this is a layout..not a control. Using DataGrid control u can create same no. of rows as in ur db
Abirami
Commented on 11.March 2010
Hi Christ,the link to 'How to create a resizable column' is broken..
Article Not Found error occurs.
Hukam
Commented on 4.May 2010
Awesome ...:)
Johnny
Commented on 7.May 2010
Really nice one. thanks....
Hiren Solanki
Commented on 14.May 2010
It was pleasing experiance learning from your turorial. thanks for writing
spellchecker
Commented on 17.May 2010
it\'s Length, not Lenght :)
Christian...
Commented on 21.May 2010
Thanks Spell Checker. Now onwards please dont comment like this . if you want to make comment then please make it for good cause not to hurt anyone. Thanks and Give my regards to your family. Thanks for correcting my mistakes and now onward please make sure that you keep this going and make others happy by your comment and further more if you want to make any kind of comment then please send me to my mail christian.mosers@wpftutorial.net... dont expose it in public.. so dont forget to dispose this comment thanks
MohitB
Commented on 26.May 2010
Excelent, Its helped me alot to learn WPF.
Nitin Sharma
Commented on 28.May 2010
Dear All,
Plz do the comment as good as u can.Dont hurt any one by giving all these comments. This website helps you a lot for learning WPF technology.
Anand
Commented on 1.June 2010
Hi Christian,
Excellent effort made so far. It will be nice if comments are kept seperate (optionally in a pop up)
BARaabaz
Commented on 4.June 2010
Does it work???????
hiren solanki
Commented on 10.June 2010
@baraabaz,@Anand : please give quality comment . dont fill the page with your non-intresting PJs. plase fill free to mail me.
Christoph
Commented on 23.June 2010
Could you explain and give an example for the construct

<Grid.RowDefinitions>
<RowDefinition Height="1.1*"/>
<RowDefinition Height="8.9*"/>
</Grid.RowDefinitions>

which I found in someones' code.


Praveen...
Commented on 14.July 2010
Actully its nice but this would be better if it involves the detail about 2d.I am working right now at wpf. Its a great architecture.I have some queries, how to bind my database with treeview in wpf??
Any person can suggest me.

Thanks in advance.
Vidya Sagar...
Commented on 22.July 2010
How can I change the XAML Grid column width from c# file
Vidya Sagar...
Commented on 27.July 2010
yes, I got the answer
give Name property to the column then access that column in C# file in this way
column_treeview.Width = GridLength.Auto;
Jayesh...
Commented on 3.August 2010
Hi, Really good infromation

Regards,
Jayesh Prajapati.
Mumbai - Indaia.
Darshit Dave
Commented on 10.August 2010
Wow... I loved this style of sharing information with us... I am going to go through all the pages very soon... Thanks.
amol
Commented on 10.August 2010
how to use "Fixed" in height or width? It is not working plz explain
a
Commented on 21.August 2010
aaa
vucuongkg
Commented on 24.August 2010
Thank! :)
manu
Commented on 7.September 2010
good
Raman
Commented on 9.September 2010
When the splitter to the right end the column goes beyond the boundary. How one can limit the size of column?
luxmi
Commented on 13.September 2010
romba nallairakada
aa
Commented on 15.September 2010
2714345
DCC
Commented on 16.September 2010
Is there a way to add a displayed line between each of the grid rows? Similiar to adding a border to a cell in Excel
gg
Commented on 20.September 2010
awesome
Priya
Commented on 15.October 2010
IT help me very much.
Thanks
YJ
Commented on 16.October 2010
GridSplitter in this article is not working.
use the code below
<GridSplitter
Grid.Row="1"
Width="Auto"
Height="3"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch"
Margin="0"/>

reference: http://codebetter.com/blogs/steve.hebert/archive/2008/04/16/creating-a-horizontal-gridsplitter-for-real.aspx
Nitesh
Commented on 4.November 2010
Very helpful to me
Thank you.
Srinivas...
Commented on 6.November 2010
Nice & quick tutorial to learn WPF.
sam
Commented on 24.November 2010
I dont want anything
AntiPriya
Commented on 26.November 2010
@Priya - actaully IT Helps the whole world :)
gregg...
Commented on 26.November 2010
very helpful. tx
Cyril Gupta
Commented on 5.December 2010
Thank you for this great and simple tutorial.It is very useful.
Suguna
Commented on 16.December 2010
Superb............
selva
Commented on 29.December 2010
gridName.ColumnDefinitions(0).Width = New GridLength(70, GridUnitType.Star)
greg
Commented on 30.December 2010
Thanks--clear and concise.
hem
Commented on 21.January 2011
really too gud
jinal
Commented on 21.January 2011
its rly nice thanks
Ayyappan
Commented on 25.January 2011
I Heart fully,

Thank you for your nice Material

warm regards,

Ayyappan,

Software Engineer ,

Chennai,

Tamil Nadu.

http://www.banyansoft.blogspot.com/
lover
Commented on 27.January 2011
I love this
lesnier
Commented on 3.February 2011
i speak spanish, i´am of Cuba...
everything that i learn in this page is sufficent...
thank
wibowo
Commented on 10.February 2011
Thank you for the tutorial.
Shweta Patel
Commented on 14.February 2011
Hey Christian,
Can u tell me how can we span rows or columns in grid as we do in HTML tables...?
Gindi
Commented on 16.February 2011
Hi,
How to change grid row background color
Rahul Ranjan...
Commented on 17.February 2011
This article very nice.
Vinke
Commented on 8.March 2011
Good article, simple and precise.
beginner
Commented on 11.March 2011
Good one... I started
Shai
Commented on 15.March 2011
Its easy to understand than anyother tutorial... Thanks
Kev
Commented on 15.March 2011
Hey Shweta,
Just use the Grid.RowSpan
e.g <GridSplitter HorizontalAlignment="Right" VerticalAlignment="Stretch" Grid.RowSpan="4" Grid.Column="0" ResizeBehavior="CurrentAndNext" Width="5" Background="#FFBCBCBC" />
Manish
Commented on 19.March 2011
How can i Sort Grid Row (Assending / Dessending)
Sanjay Patolia
Commented on 26.March 2011
Can anybidy tell me why Grid.Collumn and Grid.Row are an Attached properties?
Sanjay Patolia
Commented on 26.March 2011
Nice one
Antony Nadan
Commented on 30.March 2011
Nice one Bro...
Ričardas
Commented on 30.March 2011
I have a problem with Grid inside ItemsControl. The Grid as DataTemplate with 1 row and 3 columns (each must have Width = Auto). When I populate buttons, they are shown with different widths (according to text lengths) - HorizontalAlignment=&quot;Stretch&quot; does not work. It fails to preserve same column width in each populated grid. Setting Column width to * is not an option to me, because sometimes I have one or two not visible columnns, and I want remaining visible columns (e.g. buttons) take whole width. The Grid.IsSharedSizeScope=&quot;True&quot; also does not help...

Paul
Commented on 31.March 2011
differenz types =&gt; different types
Great article. Thanks! You have some more typos in your tutorails, especially some if insted of it. I'll try to add it in comments in respectfull pages.
Om Prakash
Commented on 21.April 2011
Superb.........,
I Heart fully,

Thank you for your nice Material


Om Prakash Bishnoi
Software Engineer ,
DotSquare, Jaipur(RAj.)
Dennis
Commented on 5.May 2011
This is my firts time to use WPF, It is a great help. Keep it up man! Thanks
Arun
Commented on 5.May 2011
its very easy to learn as beginner
sandeep sharma
Commented on 5.May 2011
Fantastic Article...Well explained..
Ray Akkanson
Commented on 18.May 2011
We need more details.
Ra Akkanson
Simi
Commented on 19.May 2011
Hi,
that my first time to using grid layout.
So can u tell me d proper way that how can i run any program.
Manoj
Commented on 23.May 2011
Good One...........:-)
ray akkanson
Commented on 28.May 2011
thanks for the good explanation.
forogh
Commented on 5.June 2011
Thanks it was very helpfull, it is my first time using Grid
J
Commented on 14.June 2011
Nice one
Ashu
Commented on 21.June 2011
btf..nice article
Rakhi
Commented on 30.June 2011
its a very nice....
Tomer Avni
Commented on 12.July 2011
Thanks for this. I keep finding myself getting back to your web (which is both well organized and presented) and your topics are great !
B.T.W the part of GridLength(1,GridUnitType.Star) gave me the solution I was looking for the past 2 hours! (I couldn't help but creating element in code rather the XAML)
G2One Network
Commented on 30.July 2011
thank for sharing your great think.....
kisalay
Commented on 1.August 2011
How we can retrieve values of each column by iterating ?????
periyasamy
Commented on 3.August 2011
Thanks,this definition is very useful
Vijay
Commented on 16.August 2011
Nice
yeda anna
Commented on 25.August 2011
kya hai ye sab Ha ?????????????????????????????
yeda anna
Commented on 25.August 2011
how sexy is this documents
sreenivas
Commented on 8.September 2011
Good to learn
Gagan M
Commented on 9.September 2011
Hi,
I just found a typo. Will be better if you can get it rectified since it might be confusing for others.

In 'Define Rows and Columns' section,
'The following example shows a grid with three rows and two columns.' (Instead there are four rows and two columns in the example)

Thanks.
Randy
Commented on 22.September 2011
Thanks~ It is easy to understand for me !

Name
E-Mail (optional)
Comment