Search code examples
c#wpfinheritancemessage-passing

Trouble in Passing Value from one Window to Other in WPF C#


I am not able to understand what's wrong going in with my code.

Two Windows (window1 , window2 )

I have a button(button1) and a textBox(textBox1) on window1 and another button(button2) and a textBox(textBox2) on window2

WHAT I WANT:

is when I press button1, window2 will open as a dialogueBox, then whatever I write in textBox2 and press button2 should redirect to window1 with my text in textBox1.

PROBLEM:

is when I click button2, there is no transfer of data to textbox1, It remains Empty.

MY CODE:

public partial class window1: Window
{
    public Window1()
    {
        InitializeComponent();
        textbox.text=cd;
    }

    private string cd;
    public string getCode
    {
        get { return cd; }
        set { cd = value; }

    }


    private void button_Click_1(object sender, RoutedEventArgs e)
    {
        Window2 win2 = new Window2();

        this.Close();
        win2.ShowDialog();
    }

}

and this is other window:

public partial class Window2 : Window
{


    private void button_Click(object sender, RoutedEventArgs e)
    {
        Window1 win1 = new Window1();
        win1.getCode = textBox.Text;
        this.Close();
    }
}

Any Suggestion would be much appreciated.!


Solution

  • You need to pass reference to Window1 to child window:

    private void button_Click_1(object sender, RoutedEventArgs e)
    {
        Window2 win2 = new Window2();
        win2.Wnd1Reference = this;
    
        this.Visibility = Visibility.Collapsed;
        win2.ShowDialog();
    }
    
    public partial class Window2 : Window
    {
        public Window1 Wnd1Reference {get; set;}
    
        private void button_Click(object sender, RoutedEventArgs e)
        {
            Wnd1Reference.getCode = textBox.Text;
            this.Close();
            Wnd1Reference.Visibility = Visibility.Visible;
        }
    }