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
Pass the whole window
this will be MainWindow
Window2 newWindow = new Window2(this);
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 .
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).