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

前端 未结 3 829
时光说笑
时光说笑 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-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 .

提交回复
热议问题