form1
有一个按钮btnInvoke
,它会调用form2
。 form2
包含一个文本框和一个按钮btn2
。
用户必须在textbox
中输入数据并按下btn2
。
当点击btn2
时,form2
必须将textbox data
发送到form1
。
我尝试通过构造函数传递数据,但是我无法初始化一个新的form1
实例。
我该怎么办?
form1
有一个按钮btnInvoke
,它会调用form2
。 form2
包含一个文本框和一个按钮btn2
。
用户必须在textbox
中输入数据并按下btn2
。
当点击btn2
时,form2
必须将textbox data
发送到form1
。
我尝试通过构造函数传递数据,但是我无法初始化一个新的form1
实例。
我该怎么办?
有两种方法可供使用。第一种是使用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; }
}
}
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
中的文本。Window
而不是 Form
命名你的窗口。Form 通常用于 WinForm 应用程序。这可能有点过度,但是使用 EventAggregator
可能是一个不错的解决方案。它可以让你在 form1
中引发一个事件,然后从 form2
订阅该事件。
有一些实现 EventAggregator
的细节和示例可以在 https://stackoverflow.com/questions/2343980/event-aggregator-implementation-sample-best-practices 中找到。
由于您正在使用WPF,请使用CommandBindings和Messaging。我还建议您仔细研究MVVM框架,我更喜欢MVVM Light Toolkit。该框架有很多教程,只需向谷歌提问即可。