我有一个StackPanel内的两个网格。第一格栅被命名为为gridx。最初,网格内,有文本框(RowDefs / ColumnDefs)的2D阵列。在XAML文本框定义
<TextBox x:Name="A1" Grid.Row="4" Grid.Column="5" TextAlignment="Center" />
我想在同样的位置以编程方式添加一个TextBlock的是gridx一部分。
效果一定是这样的
<TextBlock Grid.Row="4" Grid.Column="5"
HorizontalAlignment="Left" VerticalAlignment="Top" Text="10" FontSize="8"/>
如何增加这一点。我曾经尝试这样做:
TextBlock tblock = new TextBlock();
GridX.SetColumn(tblock, cIndex);
GridX.SetRow(tblock, rIndex);
但是失败了。
我再次尝试这样做:
int rIndex = Grid.GetRow(txtBox);
int cIndex = Grid.GetColumn(txtBox);
TextBlock tblock = new TextBlock();
tblock.VerticalAlignment = VerticalAlignment.Top;
tblock.HorizontalAlignment = HorizontalAlignment.Left;
tblock.FontSize = 8;
tblock.Text = rc[i, j - 1];
Grid.SetColumn(tblock, cIndex);
Grid.SetRow(tblock, rIndex);
txtBox.MaxLength = 1;
现在的问题是,TextBlock中是不可见的。文本框隐藏它。我感谢您的帮助。
对于附加属性,您可以调用的SetValue您要指派该值的对象:
tblock.SetValue(Grid.RowProperty, 4);
或者调用静态设置方法(而不是一个实例方法像你试过)对所有者类型的财产,在这种情况下SetRow:
Grid.SetRow(tblock, 4);
下面是一个例子可能帮助别人:
Grid test = new Grid();
test.ColumnDefinitions.Add(new ColumnDefinition());
test.ColumnDefinitions.Add(new ColumnDefinition());
test.RowDefinitions.Add(new RowDefinition());
test.RowDefinitions.Add(new RowDefinition());
test.RowDefinitions.Add(new RowDefinition());
Label t1 = new Label();
t1.Content = "Test1";
Label t2 = new Label();
t2.Content = "Test2";
Label t3 = new Label();
t3.Content = "Test3";
Label t4 = new Label();
t4.Content = "Test4";
Label t5 = new Label();
t5.Content = "Test5";
Label t6 = new Label();
t6.Content = "Test6";
Grid.SetColumn(t1, 0);
Grid.SetRow(t1, 0);
test.Children.Add(t1);
Grid.SetColumn(t2, 1);
Grid.SetRow(t2, 0);
test.Children.Add(t2);
Grid.SetColumn(t3, 0);
Grid.SetRow(t3, 1);
test.Children.Add(t3);
Grid.SetColumn(t4, 1);
Grid.SetRow(t4, 1);
test.Children.Add(t4);
Grid.SetColumn(t5, 0);
Grid.SetRow(t5, 2);
test.Children.Add(t5);
Grid.SetColumn(t6, 1);
Grid.SetRow(t6, 2);
test.Children.Add(t6);
for (int i = 0; i < 6; i++)
{
test.ColumnDefinitions.Add(new ColumnDefinition());
Label t1 = new Label();
t1.Content = "Test" + i;
Grid.SetColumn(t1, i);
Grid.SetRow(t1, 0);
test.Children.Add(t1);
}