[英]C# - How to Transfer Information Between User Control
我正在做一個應用程序,用戶在文本框內輸入一個值,然后他在同一用戶控件中按下一個按鈕。 然后,來自文本框的結果將顯示在其他用戶控件的標簽上。 兩個用戶控件都處於相同的Windows窗體中。
謝謝!
最常見的方法是使用事件。 這就是我要做的:
首先定義一個EventArgs:
public class MyEventArgs : EventArgs
{
public string Text { get; private set; }
public MyEventArgs(string Text)
{
this.Text = Text;
}
}
然后在您的UserControl(帶有按鈕的控件)中:
public partial class MyUserControl
{
public event EventHandler<MyEventArgs> ButtonClicked;
public MyUserControl()
{
//...
button1.Click += (o, e) => OnButtonClicked(new MyEventArgs(textBox1.Text));
}
protected virtual void OnButtonClicked(MyEventArgs args)
{
var hand = ButtonClicked;
if(hand != null) ButtonClicked(this, args);
}
}
然后,在表單中訂閱MyUserControl.ButtonClicked
事件,並在第二個控件中調用一個方法。
請注意,如果按鈕的行為與文本框中的文本實際上不相關,則可以使用屬性獲取輸入的文本,並使用事件的空EventArgs
代替。
PS名稱MyEventArgs
, MyUserControl
和ButtonClicked
僅用於演示目的。 我鼓勵您在代碼中使用更具描述性/相關性的命名方式。
嘗試這個:
public class FirstUserControl:UserControl
{
Public event EventHandler MyEvent;
//Public property in your first usercontrol
public string MyText
{
get{return this.textbox1.Text;} //textbox1 is the name of your textbox
}
private void MyButton_Clicked(/* args */)
{
if (MyEvent!=null)
{
MyEvent(null, null);
}
}
//other codes
}
public class SecondUserControl:UserControl
{
//Public property in your first usercontrol
public string MyText
{
set{this.label1.Text = value;} //label1 is the name of your label
}
//other codes
}
然后在您的MainForm中:
public class MainForm:Forms
{
//Add two instance of the UserControls
public MainForm()
{
this.firstUserControl.MyEvent += MainWindow_myevent;
}
void MainWindow_myevent(object sender, EventArgs e)
{
this.secondUserControl.MyText = this.firstUserControl.MyText;
}
//other codes
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.