在主窗口窗体中使用线程技术创建的chlid窗口窗体中有一个子文本框控件,我想实现这个功能:在子窗口窗体中,当我单击一个按钮(或按Enter键)时,它将文本传递给主窗口表单。我该怎么办?
答案 0 :(得分:0)
快速谷歌会带给你大量的结果......
最好的办法可能就是当你创建Form2(子)有一个公共方法可用时你可以传入Form1的实例(父类)然后在Form1上再次传递相同但传递一个字符串而不是一个字符串表格的实例。所以你最终会得到这样的东西:
Form1(父母):
private void Button1_Click_ShowChildForm(args..)
{
Form2 frm2 = new Form2();
frm2.Show();
frm2.GetInstance(this);
}
public void PassBack(string var)
{
TextBox1.Text = var;
}
Form2(孩子):
private static Form1 _frm1;
public void GetInstance(Form1 Frm1)
{
this._frm1 = Frm1;
}
private void Button2_Click_Close(args...)
{
_frm1.PassBack(this.TextBox2.Text);
this.Close();
}
像那样^^^应该做的伎俩。 ;)
NB。您可以稍微整理一下,如果您真的想要,可以覆盖Form2的Show方法来接受Form1的实例,而不是声明一个单独的方法,但是你明白了。
答案 1 :(得分:0)
ChildWindow 需要一种方法将消息发送回 MainWindow 。以下示例应该很有用:
public interface IListner
{
void Send(String message);
}
主窗口
public partial class MainWindow : Window, IListner
{
public MainWindow()
{
InitializeComponent();
}
public void Send(string message)
{
// Read the message here.
// If this code is called from different thread, use "Dispatcher.Invoke()"
}
public void OpenAnotherWindow()
{
// Since "MainWindow" implements "IListner", it can pass it's own instance to "ChildWindow"
ChildWindow childWindow = new ChildWindow(this);
}
}
ChildWindow:
public partial class ChildWindow : Window
{
private IListner Listner { get; set; }
public ChildWindow(IListner listner)
{
InitializeComponent();
Listner = listner;
}
private void OnTextBoxTextChanged()
{
// This will call "Send" on "MainWindow"
Listner.Send(TextBox1.Text);
}
}