tags:

views:

926

answers:

3
+2  Q: 

XAML - In C#

Hi just trying to get my head around XAML.

Thought that I would try some writing XAML in code.

Trying to add a grid with 6 by 6 column definitions then add a textblock into one of the grid cells.

I dont seem to be able to reference the cell that I want - there is no method on the grid that I can add the textblock too. Just grid.children.add(object). No Cell definition.

TIA

The XAML

<Page x:Class="WPF_Tester.Page1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Page1"
    Loaded="Page_Loaded">

</Page>

The C# private void Page_Loaded(object sender, RoutedEventArgs e) {

        //create the structure

        Grid g = new Grid();
        g.ShowGridLines = true;
        g.Visibility = Visibility.Visible;


        //add columns
        for (int i = 0; i < 6; ++i)
        {
            ColumnDefinition cd = new ColumnDefinition();
            cd.Name = "Column" + i.ToString();

            g.ColumnDefinitions.Add(cd);
        }
        //add rows
        for (int i = 0; i < 6; ++i)
        {
            RowDefinition rd = new RowDefinition();
            rd.Name = "Row" + i.ToString();

            g.RowDefinitions.Add(rd);
        }
        TextBlock tb = new TextBlock();
        tb.Text = "Hello World";

        g.Children.Add(tb);

    }

update

Thanks for the answers however here is the spooky bit...

  • Using VS2008 Pro on XP

  • WPFbrowser Project Template (3.5 verified)

I dont get the methods in the autocomplete.

+4  A: 

WPF makes use of a funky thing called attached properties. So in your XAML you might write this:

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

And this will effectively move the TextBlock into cell (0,0) of your grid.

In code this looks a little strange. I believe it'd be something like:

g.Children.Add(tb);
Grid.SetRow(tb, 0);
Grid.SetColumn(tb, 0);

Have a look at that link above - attached properties make things really easy to do in XAML perhaps at the expense of intuitive-looking code.

Matt Hamilton
A: 

The cell location is an attached property - the value belongs to the TextBlock rather than Grid. However, since the property itself belongs to Grid, you need to use either the property definition field or the provided static functions.

TextBlock tb = new TextBlock();
//
// Locate tb in the second row, third column.
// Row and column indices are zero-indexed, so this
// equates to row 1, column 2.
//
Grid.SetRow(tb, 1);
Grid.SetColumn(tb, 2);
Zooba
A: 

Use attached properties of the Grid class.

in C#:

Grid.SetRow( cell, rownumber )

In XAML:

<TextBlock Grid.Row="1" />

Also, I would advice if you do not use dynamic grids, use the XAML markup language. I know, it has a learning curve, but once you mastered it, it is so much easier, especially if you are going to use ControlTemplates and DataTemplates! ;)

Arcturus