【问题标题】:How can I dynamically add TextBox to Grid?如何将 TextBox 动态添加到 Grid?
【发布时间】:2014-10-02 07:23:44
【问题描述】:

我正在尝试以编程方式在我的网格中添加TextBox

这是我的代码:

private async void NavigationHelper_LoadState(object sender, LoadStateEventArgs e)
        {
            var input= await OneListDataSource.GetItemAsync((string)e.NavigationParameter);
 foreach (string item in input.getItems()) {
            TextBox textBox = new TextBox();
                textBox.Text = item;
                grid.RowDefinitions.Add(new RowDefinition());
                grid.Children.Add(textBox);
            }
}

在我的 xaml 中:

<Grid Grid.Row="1" x:Name="ContentRoot" Margin="19,9.5,19,0">

        </Grid>

但是当我在模拟器中运行它时,我只看到 1 行并且所有项目似乎相互重叠。 我尝试在我的 xaml 文件中删除 Grid.Row,但我认为它没有任何区别。

更新:

感谢您的回答,我几乎可以正常工作了。现在我的问题是 为什么我需要添加一个新的 RowDefintion() 一切我添加一个新的 children(),我可以在没有 RowDefinitions.Add(new RowDefinition()) 的情况下为每一行添加吗?

foreach (string item in input.getItems()) {
            TextBox textBox = new TextBox();
                textBox.Text = item;
                grid.RowDefinitions.Add(new RowDefinition());  // why I need to do this everytime I add a new TextBox?
                Grid.SetRow(textBox, i++);
                Grid.SetColumn(textBox, 0);
                grid.Children.Add(textBox);
            }

【问题讨论】:

标签: c# xaml


【解决方案1】:

需要 RowDefinition,因为这是 Grid 控件处理其子项的方式。如果 Grid 内的两个控件位于同一行和列中,它们将根据添加到 Grid 的顺序相互叠加。 Grid 控件不尊重它所包含的控件的边界,它只关心每一行和每一列中有哪些控件。但是,WrapPanel 不需要行和列。它将以“类似网格”的方式定位它包含的控件,直到它根据 Orientation 属性的值达到自身的宽度或高度边界。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-15
    • 1970-01-01
    • 2015-05-08
    • 1970-01-01
    • 2017-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多