How do I create WPF controls via code

I was attempting to get my head around XAML and also assumed that I would certainly attempt creating some code.

Attempting to add a grid with 6 by 6 column interpretations after that add a message block right into among the grid cells. I do not appear to be able to reference the cell that I desire. There is no method on the grid that I can add the message block also. There is just grid.children.add (object), no Cell definition.


<Page x:Class="WPF_Tester.Page1"



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();

    //add rows
    for (int i = 0; i < 6; ++i)
        RowDefinition rd = new RowDefinition();
        rd.Name = "Row" + i.ToString();

    TextBlock tb = new TextBlock();
    tb.Text = "Hello World";



Here is the creepy little bit:

  • Using VS2008 Pro on XP

  • WPFbrowser Project Template (3.5 validated)

I do not get the approaches in autocomplete.

2019-05-18 22:09:42
Source Share
Answers: 3

The cell area is an affixed building - the value comes from the TextBlock as opposed to Grid. Nonetheless, given that the building itself comes from Grid, you require to make use of either the building definition area or the given fixed features.

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);
2019-05-21 06:09:55

WPF takes advantage of a fashionable point called attached properties. So in your XAML you could write this:

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

And this will properly relocate the TextBlock right into cell (0,0) of your grid.

In code this looks a little weird. I think it would certainly be something like:

Grid.SetRow(tb, 0);
Grid.SetColumn(tb, 0);

Have an appearance at that link over - affixed buildings make points actually simple in XAML probably at the expenditure of instinctive - looking code.

2019-05-21 06:09:33

Use affixed buildings of the Grid class.

in C#:

Grid.SetRow( cell, rownumber )


<TextBlock Grid.Row="1" />

Also, I would certainly suggestions if you do not make use of vibrant grids, make use of the XAML markup language. I recognize, it has a finding out contour, once you understood it, it is a lot less complicated, specifically if you are mosting likely to make use of ControlTemplates and also DataTemplates! ;)

2019-05-21 06:07:57