WPF形式之间传递数据 [英] Passing data between WPF forms

查看:99
本文介绍了WPF形式之间传递数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Form1中有一个按钮btnInvoke 它调用窗口2 窗口2 包含文本按钮BTN2

form1 has a button btnInvoke which invokes form2. form2 contains a textbox and a button btn2.

用户必须输入文本和preSS BTN2 数据。

The user has to enter data in textbox and press btn2.

BTN2 点击窗口2 需要发送文本数据 Form1中

我曾尝试通过构造函数,但我不能启动 Form1中的新实例。

I have tried passing through constructors but I cant initiate a new instance of form1.

我该怎么办?

推荐答案

有,您可以使用两种方法。其中第一个是使用的ShowDialog和一个公共方法,然后测试该DialogResult的是真的,然后从方法读取值。

There are two methods that you can use. The first of which would be using ShowDialog and a public method then testing that the DialogResult is true then reading the value from the method.

if (newWindow.ShowDialog() == true)
            this.Title = newWindow.myText();

第二种方法是创建一个自定义事件和订阅它在这样的创建窗口。

The second method would be to create a CustomEvent and subscribe to it in the creating window like this.

MainWindow.xaml.cs

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, RoutedEventArgs e)
    {
        Window1 newWindow = new Window1();
        newWindow.RaiseCustomEvent += new EventHandler<CustomEventArgs>(newWindow_RaiseCustomEvent);
        newWindow.Show();

    }

    void newWindow_RaiseCustomEvent(object sender, CustomEventArgs e)
    {
        this.Title = e.Message;
    }
}

Window1.xaml.cs

public partial class Window1 : Window
{
    public event EventHandler<CustomEventArgs> RaiseCustomEvent;

    public Window1()
    {
        InitializeComponent();
    }
    public string myText()
    {
        return textBox1.Text;
    }
    private void button1_Click(object sender, RoutedEventArgs e)
    {

        RaiseCustomEvent(this, new CustomEventArgs(textBox1.Text));
    }
}
public class CustomEventArgs : EventArgs
{
    public CustomEventArgs(string s)
    {
        msg = s;
    }
    private string msg;
    public string Message
    {
        get { return msg; }
    }
}

这篇关于WPF形式之间传递数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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