How can I dynamically associate a TextBlock with a Grid's Column?

I want to dynamically create a 1-row grid and add some TextBlocks to it, assigning/associating each one to a different column in the grid. I've got this code:

SolidColorBrush samHagar = new SolidColorBrush(Colors.Red);
System.Windows.Thickness mrg = new Thickness(2);

// Create a Grid
Grid grd = new Grid();
. . . // TODO: add columns
//...add the Grid to the StackPanel
spNufan.Children.Add(grd);

// Create TextBlock and dynamically add it  to the Grid
TextBlock tbDynamo = new TextBlock();
tbDynamo.Background = samHagar;
tbDynamo.TextWrapping = TextWrapping.Wrap;
//tbDynamo.Grid.Column = 0; <- no go, Joe!
tbDynamo.Margin = mrg;
tbDynamo.TextAlignment = TextAlignment.Left;
tbDynamo.VerticalAlignment = VerticalAlignment.Center;
tbDynamo.Text = "Whatever";
spNufan.Children.Add(grd);

How can I affiliate my TextBlock ("tbDynamo") with my Grid ("grd")?

Upvotes: 0

Views: 1479

Answers (3)

Rachel
Rachel

Reputation: 132548

Set the object's Grid.Column property, then add the object to the Grid

Grid.SetColumn(tbDynamo, 0);
grd.Children.Add(tbDynamo);

As a side note, you don't actually need to set it to 0 since items in a Grid will default to Grid.Row=0 and Grid.Column=0 unless otherwise specified.

Upvotes: 3

Henk Holterman
Henk Holterman

Reputation: 273179

It should be something like

// untested    
// spNufan.Children.Add(grd);  // already done earlier
grd.Children.Add(tbDynamo);
Grid.SetRow(tbDynamo, i);

But I would seriously look into StackPanel and ListBox first. They seem more appropriate than a Grid.
How do you want scrolling to look?

Upvotes: 1

Daniel Hilgarth
Daniel Hilgarth

Reputation: 174299

You need to use Grid.SetColumn(tbDynamo, 0);

Upvotes: 1

Related Questions