简体   繁体   中英

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")?

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.

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?

您需要使用Grid.SetColumn(tbDynamo, 0);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM