Pass Data from Child Window to MainWindow TextBlock

前端 未结 5 661
臣服心动
臣服心动 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 11:09

    The answer you're looking for is very implementation-based and depends heavily on what you want Window2 as a class to do.


    private MainWindow mainwindow;
    

    This is acceptable.

    public MainWindow mainwindow { get; private set; }
    

    This would work but doesn't respect naming conventions because it's a property. Usually you'd use this for encapsulation of a field or for easy access to a computed value.

    public Window MainWindow { get; set; }
    

    This is not acceptable in your context because Window does not contain a textBlockMessage.

    private object mainwindow { get; private set; };
    

    This also wouldn't work for the same reason as above.

    private MainWindow mainwindow = ((MainWindow)System.Windows.Application.Current.MainWindow);
    

    This would work and would even let you not keep a field for the reference to the MainWindow instance in your Window2 instances. Still needs to get that MainWindow everytime you click the button however.


    Another interesting way to do what you're doing however is to simply pass the handler to the child windows at instanciation:

    MainWindow

    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
    
        // Open Window 2
        private void buttonWindow2_Click(object sender, RoutedEventArgs e)
        {
            Window2 window2 = new Window2(); // No need to give a reference to the child window anymore
            window2.setClickHandler((obj, ev) => {
                textBlockMessage.Text = "Hello, world!"; // Direct access to the textblock.
            });
            window2.Left = Math.Max(this.Left - window2.Width, 0);
            window2.Top = Math.Max(this.Top - 0, 0);
            window2.ShowDialog();
        }
    }
    

    Window2

    public partial class Window2 : Window
    {
        public Window2()
        {
            InitializeComponent();
        }
    
        public void setClickHandler(RoutedEventHandler handler)
        {
            // The handler is given to the click event.
            buttonMessage.Click -= handler;
            buttonMessage.Click += handler;
        }
    }
    

    And with that your Window2 class has no need to know MainWindow.

提交回复
热议问题