在WPF窗体之间传递数据

3

form1有一个按钮btnInvoke,它会调用form2form2包含一个文本框和一个按钮btn2

用户必须在textbox中输入数据并按下btn2

当点击btn2时,form2必须将textbox data发送到form1

我尝试通过构造函数传递数据,但是我无法初始化一个新的form1实例。

我该怎么办?


3
请展示你尝试过的代码。 - Ravi Y
1
在form2中创建一个事件,并让form1订阅它。然后当btn2被点击时,调用该事件。 - Surfbutler
1
请查看Application.Current.Properties。 - Pavel Voronin
4个回答

10

有两种方法可供使用。第一种是使用ShowDialog和一个公共方法,然后测试DialogResult是否为true,然后从该方法中读取值。

例如:

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

第二种方法是创建一个CustomEvent并在创建窗口中订阅它,如下所示。

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; }
    }
}

1
在你的form1中定义一个公共属性。
public string MyTextData { get; set; }

在您的form2中,当按钮被点击时,获取form1的实例并将其属性设置为TextBox的值。
var frm1 = Application.Current.Windows["form1"] as Form1;
if(frm1 ! = null)
    frm1.MyTextData  = yourTextBox.Text;

在你的 Form1 中,你将会得到你的属性 MyTextData 中的文本。
最好遵循命名窗口的惯例。在 WPF 中,使用 Window 而不是 Form 命名你的窗口。Form 通常用于 WinForm 应用程序。

"form1"不起作用。它必须是一个整数。什么整数? - matsolof

1

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接