简体   繁体   English

如何动态地将TextBlock与网格的列关联?

[英]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. 我想动态创建一个1行的网格并向其中添加一些TextBlock,将每个网格分配/关联到网格中的不同列。 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")? 如何将TextBlock(“ tbDynamo”)与网格(“ grd”)关联?

Set the object's Grid.Column property, then add the object to the Grid 设置对象的Grid.Column属性,然后将对象添加到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. 附带说明一下,您实际上不需要将其设置为0,因为除非另有说明,否则Grid项目将默认为Grid.Row=0Grid.Column=0

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. 但是我会认真研究一下StackPanel和ListBox。 They seem more appropriate than a Grid. 它们似乎比网格更合适。
How do you want scrolling to look? 您想如何滚动外观?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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