Home > Enterprise >  How can I use the window1 text box value in the field in the main window?
How can I use the window1 text box value in the field in the main window?

Time:03-24

I have two windows: Mainwindow and window1. Window1 has a textbox. Mainwindow has a label and button. When I click the button the value in the textbox will be added to the label. I need cs code, please!

// Mainwindow.xaml

<Grid>
        <StackPanel>
            <Label Name="lbl" Content="0" FontSize="150"/>
            <Button x:Name="mushtbtn" Height="50" Content="Add " Click="mushtbtn_Click"  />
            <Button x:Name="newWindow" Content="Show Window1" Height="50" Click="newWindow_Click"/>
        </StackPanel>
</Grid>

//Window1.xaml

<Grid>
        <StackPanel>
            <TextBox x:Name="txtbox"  FontSize="50"/>
            <Button x:Name="closebtn" Content="Save and close" Height="50" Click="closebtn_Click"/>
        </StackPanel>
    </Grid>

CodePudding user response:

In MainWindow you can initialize a new window1 x when you click the new window button. After being initialized you can access the textbox text and asign to the main window label.

public partial class MainWindow : Window
{
    Window1? x; // added nullable check

    public MainWindow()
    {
        InitializeComponent();
    }

    private void mushtbtn_Click(object sender, RoutedEventArgs e)
    {
        if (x is not null) // check if window is initialized
        {
            lbl.Content = x.txtbox.Text;
        }
    }

    private void newWindow_Click(object sender, RoutedEventArgs e)
    {
        x = new Window1();
        x.Show();
    }
}

In the window1 all you have to do is enter text and then close();

public partial class Window1 : Window
{
    public Window1()
    {
        InitializeComponent();
    }

    private void closebtn_Click(object sender, RoutedEventArgs e)
    {
        Close();
    }
}

Don't forget to click the add button in the main window.

CodePudding user response:

In Window1 I added this code:

    private void closebtn_Click(object sender, RoutedEventArgs e)
    {
        MainWindow MW = (MainWindow)Application.Current.MainWindow;
        MW.lbl.Content = MW.lbl.Content   txtbox.Text;
        this.Close();
    }
  • Related