将值从主窗口传递到子窗口,然后从子窗口返回多个值到主窗口

时间:2017-06-30 07:54:46

标签: c# wpf

我有一个主窗口,并希望将值传递给弹出窗口(它将使用该值设置一些依赖于该值的其他值)。弹出窗口有多个用于用户输入的文本框。当按下一个名为SaveButton的按钮时,我希望用户输入(所有这些)都被发送回主窗口。我怎么能做到这一点?

我是C#的新手,我知道有类似的问题。但是,我很难根据具体情况调整答案。感谢您在回答时牢记这一点!

非常感谢你!

编辑:关于代码 我的代码: 用于启动PopUp窗口(这是一个名为PopUp的Window WPF)

PopUp popUp = new PopUp();
popUp.ShowDialog

除了标准内容和按钮点击事件的事件处理程序外,PopUp.xaml.cs为空。

2 个答案:

答案 0 :(得分:1)

看看这个:

您的主窗口:

namespace WpfApplication1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
    //Defining public or internal parameters
    public int MainWindowProp1 { get; set; }
    public string MainWindowProp2 { get; set; }

    public MainWindow()
    {
        InitializeComponent();
        this.Loaded += MainWindow_Loaded;
    }

    private void MainWindow_Loaded(object sender, RoutedEventArgs e)
    {
        //When you call your child window, pass this (mainwindow) as parameter.
        childWindow cw = new WpfApplication1.childWindow(this);
        cw.Param2 = "test";
        cw.Param1 = 12;
        cw.Closed += Cw_Closed;
        cw.ShowDialog();
    }

    private void Cw_Closed(object sender, EventArgs e)
    {
        //On closed event, you can cast the sender as your child window.
        var child = (sender as childWindow);
        var param1 = child.Param1;
        var param3 = child.Param2;
    }

    public void TestMethod()
    {
        //do anything you want
    }
}
}

和你的子窗口:

namespace WpfApplication1
{
/// <summary>
/// Interaction logic for childWindow.xaml
/// </summary>
public partial class childWindow : Window
{
    //declare Mainwindow as a parameter in your child window
    public MainWindow mainWindow;
    public int Param1 { get; set; }
    public string Param2 { get; set; }
    //Add a parameter in your child window contructor.
    public childWindow(MainWindow _mainWindow)
    {
        InitializeComponent();
        //Assign your global parameter mainWindow to the _mainWindow parameter. 
        this.mainWindow = _mainWindow;
        this.Loaded += ChildWindow_Loaded;
    }

    private void ChildWindow_Loaded(object sender, RoutedEventArgs e)
    {

        //You can get or set your main window properties. 
        this.mainWindow.MainWindowProp1 = 5;
        this.mainWindow.MainWindowProp2 = "test";

        //You can call methods ant events etc.. of your main window too (depending on acces modifiers).
      this.mainWindow.TestMethod();
    }
}
}

答案 1 :(得分:0)

总的来说,最简化的解决方案是:

从MainWindow到子窗口(Window1);

((Window1)Application.Current.Windows[1]).testlabel.Content = "In Sync";

从子窗口到MainWindow;

((MainWindow)Application.Current.MainWindow).label2.Content = "whatever";