Reputation: 10237
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
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
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