[英]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.