C # - return a variable from a child window to a parent window in WPF

I have a main window named form1. in form1, I have a button, when it is clicked, it will open form2 (form2.ShowDialog ()). In form2, I have a "Check" button. When the user clicks "Validation", he has to perform some validation and, if successful, creates a string object and returns it to form1. Any ideas on how to implement this? I do not want to return anything when the user closes the window.

+7
variables c # wpf
source share
3 answers

Create an event in the second window, the event delegate parameters contain any information that you want to convey:

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 this event to do what it needs with information:

 public class Main : Window { private Label label; public void Foo() { Popup popup = new Popup(); popup.Check += value => label.Content = value; popup.ShowDialog(); } } 
+10
source share

This can be done in several ways. The released Servy method is not bad and will do what you need. I would prefer to see that the Action<sting> passed as a parameter to the constructor and called callback , so it clears what it is used for, but this is only a preference.

Another way that does this pretty well is messaging. The MVVMLight Toolkit provides an excellent opportunity to perform 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 post this post.

 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 a message, you should be able to receive this message:

 public class MessageReceiver { public MessageReceiver() { Messenger.Default.Register<MyMessage>(this, message => Foo(message)); } public void Foo(MyMessage message) { //do stuff } } 
0
source share

This answer, although not quite on the target, will be more useful for people who themselves here can find a common solution on how to communicate between windows:

There is no reason to configure events to access the objects in the main window of your application. You can simply call them in a popup window and do with it:

 ((MainWindow)Application.Current.MainWindow).textBox1.Text = "Some text"; 
0
source share

All Articles