I have a main window called form1. in form1 I have a button, when it is pressed it will open form2 (form2.ShowDialog()). In form2 I have a button called \"Check\". When the
This answer while not perfectly on target will be more useful to people that google themselves here for the general solution of how to communicate between windows:
There is no reason at all to set up events to access objects of the Main Window of you application. You can simply call them on the popup code and be done with it:
((MainWindow)Application.Current.MainWindow).textBox1.Text = "Some text";
This could be accomplished in several ways. The method Servy posted is quite good and will accomplish what you need. I would prefer to see the Action<sting>
passed as a parameter to the constructor and named callback
so it's clear what it is used for, but that's just a preference thing.
The other method that is pretty good at getting this done is via Messaging. The MVVMLight Toolkit provides a great little feature in it for accomplishing tasks such as this.
Step 1: create a strongly typed Message:
public class MyMessage : MessageBase
{
//Message payload implementation goes here by declaring properties, etc...
}
Step 2: Determine where, and when to publish that message.
public class PublishMessage
{
public PublishMessage(){
}
public void MyMethod()
{
//do something in this method, then send message:
Messenger.Default.Send(new MyMessage() { /*initialize payload here */ });
}
}
Setp 3: Now that you are sending the message, you need to be able to receive that message:
public class MessageReceiver
{
public MessageReceiver()
{
Messenger.Default.Register<MyMessage>(this, message => Foo(message));
}
public void Foo(MyMessage message)
{
//do stuff
}
}
Create an event in your second window, have the parameters of the event's delegate contain whatever information you want to pass:
public class Popup : Window
{
public event Action<string> Check;
public void Foo()
{
//fire the event
if (Check != null)
Check("hello world");
}
}
Then the main window can subscribe to that event to do what it wants with the information:
public class Main : Window
{
private Label label;
public void Foo()
{
Popup popup = new Popup();
popup.Check += value => label.Content = value;
popup.ShowDialog();
}
}