Pass Data from Child Window to MainWindow TextBlock

前端 未结 5 697
臣服心动
臣服心动 2021-01-26 10:35

In this example, MainWindow has a button that opens Window2.

Window2 has a button that writes \"Hello, World!\" to MainWindo

5条回答
  •  独厮守ぢ
    2021-01-26 10:54

    You could declare a delegate in Window 2 and pass a function that can be executed when the button is pressed in window 2.

     public delegate void SendMessage(string Message);
     public SendMessage mainWindowDel = null;
    

    Make your constructor that accepts the delegate

     public Window2(SendMessage del)
            {
                mainWindowDel = del;
            }
    

    create window 2 by passing a function as the parameter

     public void showMessage(string Message)
     {
                    if(!string.IsNullOrWhiteSpace(Message))
                    textBlockMessage.Text = Message;
     }
     private void buttonWindow2_Click(object sender, RoutedEventArgs e)
     {
                // Open Window 2
                //Window2 window2 = new Window2(this);
                Window2 window2 = new Window2(showMessage);
                window2.Left = Math.Max(this.Left - window2.Width, 0);
                window2.Top = Math.Max(this.Top - 0, 0);
                window2.ShowDialog();
      }
    

    call the delegate when they press the button

    // Write Message to MainWindow
            private void buttonMessage_Click(object sender, RoutedEventArgs e)
            {
               mainWindowDel("Hello, world!");
            }
    

提交回复
热议问题