You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

UWP C# 如何根据用户输入的数值在跳转页面动态生成对应数量的TextBox

你需要对Page2的代码做如下修改:

第一步:修改Page2.xaml布局

先给动态生成的TextBox预留容器,这里用StackPanel做垂直布局最方便,修改后代码如下:

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>
    <TextBlock Text="以下是动态生成的输入框" 
               VerticalAlignment="Center" 
               HorizontalAlignment="Center" 
               FontSize="30" 
               Margin="0,20"/>
    <!-- 这个StackPanel用来承载所有动态生成的TextBox -->
    <StackPanel x:Name="TextBoxContainer" 
                Grid.Row="1" 
                Margin="30" 
                Spacing="15"/>
</Grid>

第二步:补充Page2.xaml.cs的生成逻辑

在页面初始化后调用生成逻辑,循环创建指定数量的TextBox并加入容器:

using System.Collections.Generic;
using Windows.UI;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media;

public sealed partial class Page2 : Page
{
    public int UserInput = (App.Current as App).UserInput; 
    public Page2()
    {
        this.InitializeComponent();
        GenerateDynamicTextBoxes();
    }

    private void GenerateDynamicTextBoxes()
    {
        // 输入合法性校验
        if (UserInput <= 0)
        {
            TextBoxContainer.Children.Add(new TextBlock 
            { 
                Text = "输入数值不合法,请返回上一页重新输入", 
                Foreground = new SolidColorBrush(Colors.Red) 
            });
            return;
        }

        // 循环生成指定数量的TextBox
        for (int i = 0; i < UserInput; i++)
        {
            var textBox = new TextBox
            {
                Header = $"输入框 {i + 1}",
                PlaceholderText = $"请输入第{i + 1}项内容",
                Width = 300,
                // Tag属性用来标记序号,后续批量读取值的时候可以做区分
                Tag = i
            };
            // 加入布局容器
            TextBoxContainer.Children.Add(textBox);
        }
    }

    // (可选工具方法)后续需要读取所有输入框内容时可以调用
    private List<string> GetAllTextBoxValues()
    {
        var result = new List<string>();
        foreach (var child in TextBoxContainer.Children)
        {
            if (child is TextBox tb)
            {
                result.Add(tb.Text);
            }
        }
        return result;
    }
}

额外优化建议(可选)

Page1的提交逻辑最好加输入校验,避免用户输入非数字/负数导致程序崩溃:

using Windows.UI.Popups;

private async void DoneButton_Click(object sender, RoutedEventArgs e)
{
    if (!int.TryParse(UserInput.Text, out int inputNum) || inputNum <= 0)
    {
        await new MessageDialog("请输入大于0的有效数字").ShowAsync();
        return;
    }
    (App.Current as App).UserInput = inputNum;
    this.Frame.Navigate(typeof(Page2));
}

注意:需要提前在App.xaml.cs中声明全局的UserInput属性,示例:

public sealed partial class App : Application
{
    public int UserInput { get; set; }
    // 其他原有代码
}

内容的提问来源于stack exchange,提问作者wpsimon09

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 19:45:06