[WPF] Set Attached Properties (Grid.Column, Grid.Row, Canvas.Top, Canvas.Left, etc.) in C# Code

Hello everybody,

if you tried to create a Grid, Canvas or a DockPanel in C# problem than you probably had the problem that you do not know how to add the children to a specific column, row or whatever.

These properties are so called Attached Properties. And you can not see them if you call textBox.Grid.Row in the C# code.

Here an example

<Grid>
   <TextBox Grid.Row="0" Grid.Column="0" />
</Grid>

But you can not do the following in your C# Code

<pre>Grid grid = new Grid();
TextBox txt = new TextBox();
txt.Grid.Column = 1; //Not possible!

But you can do the following

//Set the Grid.Row Attached Property of the TextBox txt to 0
Grid.SetRow(txt, 0);
//Set the Grid.Column Attached Property of the TextBox txt to 0
Grid.SetColumn(txt,0);

It works in the same way for all other Attached Properties

Advertisements
  1. This should have lowercase for “Grid” i.e.

    //Set the Grid.Row Attached Property of the TextBox txt to 0
    grid.SetRow(txt, 0);
    //Set the Grid.Column Attached Property of the TextBox txt to 0
    grid.SetColumn(txt,0);

      • michlG
      • May 7th, 2011

      The Grid.Row / Grid.Column properties are so called attached properties.
      SetRow / SetColumn are static methods. Therefore you can call them either directly by using the class Grid.SetRow
      Or you can call it by using an instance of the Grid class (in your case the small grid)
      You have the same result but I prefer the first version since it is a static method and there is no need to know the instance of the Grid

    • G
    • February 28th, 2012

    Thanks! 🙂

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: