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

WPF页面间TextBox文本传递问题求助:Page1文本无法同步到Page2

解决WPF页面间TextBox文本传递问题

问题根源

你当前的代码逻辑存在错误:通过NavigationService.Navigate(new Uri("Page2.xaml", ...))跳转时,WPF会新建一个Page2实例;而你后续new Page2()创建的是另一个完全独立的Page2对象,给这个对象的BTextBox赋值,根本不会影响实际跳转过去的那个页面,所以文本无法同步。

解决方案1:通过构造函数传参(最直观的新手方案)

步骤1:修改Page2的构造函数

在Page2.cs中添加带参数的构造函数,初始化时直接给BTextBox赋值:

public Page2(string inputText)
{
    InitializeComponent();
    // 直接将传入的文本赋值给BTextBox
    BTextBox.Text = inputText;
}

步骤2:修改Page1的跳转逻辑

不再通过Uri导航,而是直接导航到你创建的、已经赋值好的Page2实例:

private void AppealNumberTextBoxEnter(object sender, KeyEventArgs e)
{
    if (e.Key == Key.Return)
    {
        NavigationService ns = NavigationService.GetNavigationService(this);
        // 创建Page2实例并传入ATextBox的文本
        Page2 p2 = new Page2(ATextBox.Text);
        // 导航到这个实例
        ns.Navigate(p2);
    }
}

解决方案2:通过NavigationService传递额外参数

如果需要保留Uri导航的方式,可以用Navigate的重载传递参数,再在Page2中接收:

步骤1:修改Page1的跳转代码

private void AppealNumberTextBoxEnter(object sender, KeyEventArgs e)
{
    if (e.Key == Key.Return)
    {
        NavigationService ns = NavigationService.GetNavigationService(this);
        // 第二个参数就是要传递的额外数据
        ns.Navigate(new Uri("Page2.xaml", UriKind.Relative), ATextBox.Text);
    }
}

步骤2:在Page2中接收参数

重写OnNavigatedTo方法,在页面导航过来时获取传递的参数:

protected override void OnNavigatedTo(NavigationEventArgs e)
{
    base.OnNavigatedTo(e);
    // 检查参数是否存在,然后赋值给BTextBox
    if (e.ExtraData != null)
    {
        BTextBox.Text = e.ExtraData.ToString();
    }
}

验证效果

修改完成后,在Page1的ATextBox中输入文本并按回车,跳转后的Page2的BTextBox就会显示对应的文本,按Page2的回车也能弹出正确的提示框。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 00:30:56