C# - Return variable from child window to parent window in WPF

前端 未结 3 1653
滥情空心
滥情空心 2020-12-16 23:45

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

3条回答
  •  萌比男神i
    2020-12-17 00:24

    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 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(this, message => Foo(message));
        }
    
        public void Foo(MyMessage message)
        {
            //do stuff
        }
    }
    

提交回复
热议问题