代码之家  ›  专栏  ›  技术社区  ›  Reflux

从弹出窗口返回对象

  •  35
  • Reflux  · 技术社区  · 15 年前

    我有一个弹出另一个窗口的窗口。我希望第二个窗口能够在按下按钮时将对象返回到第一个窗口。我该怎么做?

    4 回复  |  直到 6 年前
        1
  •  48
  •   Thomas Levesque    15 年前

    您可以在第二个窗口上公开属性,以便第一个窗口可以检索它。

    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; }
        }
    
    }
    
        2
  •  19
  •   Robert Rossney    15 年前

    如果不希望公开属性,并且希望使用法更明确一点,则可以重载 ShowDialog :

    public DialogResult ShowDialog(out MyObject result)
    {
       DialogResult dr = ShowDialog();
       result = (dr == DialogResult.Cancel) 
          ? null 
          : MyObjectInstance;
       return dr;
    }
    
        3
  •  0
  •   Scott    8 年前

    我知道这是一个老版本,但我在为我正在开发的WPF应用程序寻找相同的信息。我发现这个网站非常有用:

    http://www.dreamincode.net/forums/topic/206458-the-right-way-to-get-values-from-form1-to-form2/

    这是为Windows窗体编写的,但是如果您忽略了向新窗口传递值的部分,它仍然有效,并且有一些非常好的信息。

    另一方面,要将值传递到新窗口,这非常有用:

    WPF passing string to new window

        4
  •  0
  •   Colin    7 年前

    神圣的火星母亲,我花了很长时间才明白:

    窗口1:

    if ((bool)window.ShowDialog() == true)
    {
       Window2 content = window.Content as Window2;
       string result = content.result;
       int i = 0;
    }
    

    窗口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" ... />