在 WPF 表单之间传递数据 [英] Passing data between WPF forms
问题描述
form1
有一个 button btnInvoke
调用 form2
.form2
包含一个 textbox
和一个 button btn2
.
form1
has a button btnInvoke
which invokes form2
. form2
contains a textbox
and a button btn2
.
用户必须在textbox
中输入数据并按下btn2
.
The user has to enter data in textbox
and press btn2
.
当btn2
被点击时form2
必须将textbox data
发送到form1
.
When btn2
is clicked form2
has to send textbox data
to 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();
第二种方法是创建一个 CustomEvent 并像这样在创建窗口中订阅它.
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屋!