Return an object from a popup window
I have a Window which pop-ups another Window. I want the second Window to be able to return an 开发者_如何转开发object to the first Window when a button is pressed. How would I do this?
You can expose a property on the second window, so that the first window can retrieve it.
public class Window1 : Window
{
...
private void btnPromptFoo_Click(object sender, RoutedEventArgs e)
{
var w = new Window2();
if (w.ShowDialog() == true)
{
string foo = w.Foo;
...
}
}
}
public class Window2 : Window
{
...
public string Foo
{
get { return txtFoo.Text; }
}
}
If you don't want to expose a property, and you want to make the usage a little more explicit, you can overload ShowDialog
:
public DialogResult ShowDialog(out MyObject result)
{
DialogResult dr = ShowDialog();
result = (dr == DialogResult.Cancel)
? null
: MyObjectInstance;
return dr;
}
Holy mother of Mars, this took me forever to figure out:
WINDOW 1:
if ((bool)window.ShowDialog() == true)
{
Window2 content = window.Content as Window2;
string result = content.result;
int i = 0;
}
WINDOW 2:
public partial class Window2 : UserControl
{
public string result
{
get { return resultTextBox.Text; }
}
public Window2()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
Window.GetWindow(this).DialogResult = true;
Window.GetWindow(this).Close();
}
}
XAML:
<Button IsDefault="True" ... />
I did it like that.
In parent window make a corresponding ClosingEvent like this :
private void NewWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
NewWindow nw = (NewWindow)sender;
object Receiver = nw.Sender;
}
...and in the child window change your code implement the "sender" like this :
public partial class NewWindow : Window
{
public object Sender { get; set; }
public NewWindow()
{
InitializeComponent();
Sender = objectYouWantToSend;
}
}
So when you put data into the object "Sender" in child window, while closing this window will put the data into the "Receiver" variable.
I hope, this helps.
You can simply call any method of the popup window like this:
int value = 0;
if ((bool)poupWindow.ShowDialog() == true) {
value = poupWindow.GetValue();
}
I know this is an old one, but I was looking for the same information for a WPF application I'm working on. I found this site to be really helpful:
http://www.dreamincode.net/forums/topic/206458-the-right-way-to-get-values-from-form1-to-form2/
This is written for Windows Forms, but if you ignore the part about passing values to the new window, it still worked and had some really good information.
On a side note, to pass values to the new window, this was really helpful:
WPF passing string to new window
精彩评论