How should I pass data between WPF Windows involving `MainWindow` (C#)?

前端 未结 3 823
时光说笑
时光说笑 2020-12-08 23:26

I am currently starting a C# project in which I am modelling a simple ATM machine, and will therefore need several screens. I have run into the problem of passing data betwe

相关标签:
3条回答
  • 2020-12-08 23:59

    Pass the whole window
    this will be MainWindow

    Window2 newWindow = new Window2(this);
    
    0 讨论(0)
  • 2020-12-09 00:12

    You can set the First window as the Second window's DataContext :

     namespace Banking_System
     {       
         public partial class MainWindow : Window
         {
            public MainWindow()
            {
                InitializeComponent();           
            }
    
            private void btnSwitchForm_Click(object sender, RoutedEventArgs e)
            {               
                Window2 newWindow = new Window2(strForm1Text);
                newWindow.DataContext = this;
                newWindow.ShowDialog();      
            }            
      }
    
     public partial class MainWindow2 : Window
     {
          public MainWindow2()
          {
             var window1 = this.DataContext;
          }
     }  
    

    }

    Additionally i would recommend that your Window would have it's own ViewModel set as it's DataContext which you can send to the other window. In this way you can also bind properties directly to both windows and not worry about updating them manually .

    0 讨论(0)
  • 2020-12-09 00:13

    You can actually access your application's main window without passing any references between windows. Application.Current.MainWindow returns the instance of the main window that is declared in app.xaml. It returns a Window (which your main window derives from) so you will need to cast it in order to access its members.

    For example, you could use this code in your second window:

    ((MainWindow)Application.Current.MainWindow).txtForm1TextBox.Text = "Some text";
    

    Having said that, I kindly suggest that you do some research into WPF design patterns (specifically MVVM).

    0 讨论(0)
提交回复
热议问题