[英]WPF: How can I pass the text of textbox in a thread to the main window?
在主窗口表单使用线程技术创建的chlid窗口表单中有一个子文本框控件,我想实现此功能:在子窗口表单中,当我单击按钮(或Enter-key-down)时,它将传递文本到主窗口窗体。 我该怎么办?
一个快速的谷歌将带给您大量的结果...
最好的办法可能是在创建Form2(子级)时有一个可用的公共方法,您可以在其中传递Form1的实例(父级),然后在Form1上再次传递相同的方法,但传递字符串而不是a的实例。形成。 因此,您最终将得到如下结果:
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();
}
像^^^这样的东西应该可以解决问题。 ;)
注意 您可以整理一下,如果您确实想要,可以覆盖Form2的Show方法以接受Form1的实例,而不用声明一个单独的方法,但是您明白了。
您需要让ChildWindow将消息发送回MainWindow的方法 。 以下示例将很有用:
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);
}
}
主窗口
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); } }
子窗口:
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); } }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.