消息框无法调用局部变量

时间:2018-05-16 21:56:32

标签: c# wpf wpf-controls 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;

        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);
        }

    }

编辑:感谢mjwills,我移动了“Text1 = txtbx.Text;”这是最终工作的结果:

        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;
            };
        } 

1 个答案:

答案 0 :(得分:0)

你声明:

private string Text1;

但是你只能在机会上分配:

EditChecked = True

如果

,您只显示消息
EditChecked = False

因此,如果EditChecked = False,则需要指定Text1。也许在宣言上:

private string Text1 = "My default message";