C# - 从子窗口返回变量父窗口在WPF [英] C# - Return variable from child window to parent window in WPF

查看:193
本文介绍了C# - 从子窗口返回变量父窗口在WPF的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个叫做Form1的一个主窗口。在Form1我有一个按钮,当按下它,它就会打开窗口2(form2.ShowDialog())。在窗口2我有一个所谓的检查按钮。当用户点击检查它应该做一些验证,如果成功创建了一个String对象,并使其返回到Form1。任何想法如何实现这一点?我不想回,当用户关闭窗口任何事情。

I have a main window called form1. in form1 I have a button, when it is pressed it will open form2 (form2.ShowDialog()). In form2 I have a button called "Check". When the user clicks on "Check" it should do some validation and if successful creates a string object and return it to form1. Any Ideas on how to implement this? I don't want to return anything when the user closes the window.

推荐答案

在你的第二个窗口中创建一个事件,有该事件的委托的参数包含你要传递的任何信息:

Create an event in your second window, have the parameters of the event's delegate contain whatever information you want to pass:

public class Popup : Window
{
    public event Action<string> Check;

    public void Foo()
    {
        //fire the event
        if (Check != null)
            Check("hello world");
    }
}



然后在主窗口可以订阅该事件做它想要的信息:

Then the main window can subscribe to that event to do what it wants with the information:

public class Main : Window
{
    private Label label;
    public void Foo()
    {
        Popup popup = new Popup();
        popup.Check += value => label.Content = value;
        popup.ShowDialog();
    }
}

这篇关于C# - 从子窗口返回变量父窗口在WPF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆