Pass values between windows
-
Hello,
In WPF, I open window2 from window1 with a button click keeping window1 open. When I close window2, I want to display 2 values in window1. How can this be achieved?
Thanks
Assuming the values you want to show are contained in Window2. You need to register a method to the "Closed" event of Window2. Like this;
private void StartWindow()
{
Window window2 = new Window();
window2.Closed += new EventHandler(window2_Closed);
window2.Show();
}
void window2_Closed(object sender, EventArgs e)
{
Window window2 = sender as Window;
if (window2 != null)
{
//display message
MessageBox.Show(window2.Text1);
MessageBox.Show(window2.Text2);
}
} -
Hello,
In WPF, I open window2 from window1 with a button click keeping window1 open. When I close window2, I want to display 2 values in window1. How can this be achieved?
Thanks
Try it with DataBinding. Just bind the Controls in Window1 and Window2 on the properties of the same object.
class Data : INotifyPropertyChanged
{
private int myVar;public int MyProperty { get { return myVar; } set { myVar = value; this.OnPropertyChanged("MyProperty"); } } #region PropertyChangedEvent public event PropertyChangedEventHandler PropertyChanged; protected virtual void OnPropertyChanged(string propertyName) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } #endregion
}
And e.g.
Data d = new Data();
Window1.DataContext = d;
Window2.DataContext = d;In Windows2.xaml
e.g. In Windows1.xaml
<pre lang="HTML">
<Label Content={Binding MyProperty} />
</pre>