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

MessageBox弹出空白内容,局部变量赋值时机问题求助

解决ViewChecked模式下MessageBox弹出空白的问题

我看了你遇到的问题:当Button_Click事件触发且ViewChecked为true时,MessageBox总是弹出空白内容。咱们先拆解下原代码里的问题所在:

原问题代码

private string Text1; 
public void Button_Click(object sender, RoutedEventArgs e) { 
    TextBox txtbx = new TextBox(); 
    txtbx.Height = 50; 
    txtbx.Width = 200; 
    txtbx.Margin = new Thickness(771, 282, 0, 0); 
    txtbx.Background = new SolidColorBrush(Colors.White); 
    txtbx.Foreground = new SolidColorBrush(Colors.Black); 
    Text1 = txtbx.Text; // 这里刚创建TextBox,文本为空,且后续用户输入后未更新Text1
    if (EditChecked == true) { 
        LayoutRoot.Children.Add(txtbx); 
        Button Save = new Button(); 
        Save.Height = 25; 
        Save.Width = 50; 
        Save.Content = "Save"; 
        Save.Margin = new Thickness(771, 382, 0, 0); 
        LayoutRoot.Children.Add(Save); 
        txtbx.Text = Text1; 
        Save.Click += delegate { 
            txtbx.Visibility = Visibility.Collapsed; 
            Save.Visibility = Visibility.Collapsed; 
        }; 
    } else if (ViewChecked == true) { 
        MessageBox.Show(Text1); 
    } 
}

问题核心原因

你在TextBox刚初始化时就执行了Text1 = txtbx.Text;,这时候TextBox还没有任何用户输入,文本自然是空的。更关键的是,在EditChecked模式下,用户输入内容点击Save后,你没有把输入的内容同步到Text1变量中,导致后续切换到ViewChecked模式时,Text1依然是空值,所以MessageBox显示空白。

修正后的可直接使用代码

把Text1 = txtbx.Text;移到Save按钮的点击事件里,确保用户输入的内容能被正确保存到Text1中,这样后续View模式就能正常显示内容了:

private string Text1; 
public void Button_Click(object sender, RoutedEventArgs e) { 
    TextBox txtbx = new TextBox(); 
    txtbx.Height = 50; 
    txtbx.Width = 200; 
    txtbx.Margin = new Thickness(771, 282, 0, 0); 
    txtbx.Background = new SolidColorBrush(Colors.White); 
    txtbx.Foreground = new SolidColorBrush(Colors.Black); 
    if (EditChecked == true) { 
        LayoutRoot.Children.Add(txtbx); 
        Button Save = new Button(); 
        Save.Height = 25; 
        Save.Width = 50; 
        Save.Content = "Save"; 
        Save.Margin = new Thickness(771, 382, 0, 0); 
        LayoutRoot.Children.Add(Save); 
        txtbx.Text = Text1; 
        Save.Click += delegate { 
            txtbx.Visibility = Visibility.Collapsed; 
            Save.Visibility = Visibility.Collapsed; 
            Text1 = txtbx.Text; // 这里更新Text1为用户实际输入的内容
        }; 
    } else if (ViewChecked == true) { 
        MessageBox.Show(Text1); 
    } 
}

调整后,用户在Edit模式下输入内容并点击Save,Text1就会被更新为输入的文本,之后切换到View模式点击按钮,MessageBox就能正常显示内容了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 04:11:19