以编程方式访问网格元素

时间:2017-11-25 22:28:03

标签: c# xaml uwp

我们说我有:

<Grid Name="paramGrid">
    <Grid.ColumnDefinitions>
        <ColumnDefinition/>
    </Grid.ColumnDefinitions>

    <Grid.RowDefinitions>
        <RowDefinition/>
        <RowDefinition/>
    </Grid.RowDefinitions>

    <TextBox Grid.Row="0" Grid.Column="0"/>
    <TextBox Grid.Row="1" Grid.Column="0"/>
</Grid>

我知道如何添加行/列,例如:

paramGrid.RowDefinitions.Add(new RowDefinition());

TextBox tb = new TextBox();
tb.Text = "Sample";
tb.Name = "textBox";

paramGrid.Children.Add(tb);
Grid.SetColumn(tb, 0);
Grid.SetRow(tb, 2); 

以上为新行添加TextBox

我的问题是:我现在如何访问它?我需要在新行上查询.Text的{​​{1}}属性。

1 个答案:

答案 0 :(得分:2)

保留参考文本框:

private TextBox m_Tb;

...

m_Tb = new TextBox();
m_Tb.Text = "Sample";
m_Tb.Name = "textBox";

....

something something = m_Tb.Text;

在网格的Children集合中找到它:

var tb = (TextBox)paramGrid.Children[0];
something something = tb.Text;

显然[0]仅在文本框是网格中的唯一子项或第一个子项时才有效。

相关问题