[英]Control Objects in a usercontrol from another usercontrol
在我的表單 (Form1) 中,我有 2 個用戶控件(usercontrol1 和 usercontrol1)。 在第一個用戶控件 (usercontrol1) 上是一個按鈕 (button1),在第二個用戶控件 (usercontrol2) 上是一個標簽 (label1)。 我想通過單擊按鈕“button1”來更改“label1”的文本。 我嘗試了很多東西並查看了許多論壇,但可以解決問題。
表格1
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public void changeText()
{
userControl21.label1.Text = "Test!";
MessageBox.Show("");
}
}
用戶控制1代碼
public partial class UserControl1 : UserControl
{
public UserControl1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
UserControl2 UC = new UserControl2();
UC.label1.Text = "Text!";
Form1 frm = new Form1();
frm.changeText();
}
}
用戶控制2代碼
public partial class UserControl2 : UserControl
{
public UserControl2()
{
InitializeComponent();
}
}
正如“Usercontrol1”的代碼中所見,我嘗試直接更改文本,然后嘗試通過在“Form1”上運行一種方法來更改文本,該方法可以更改文本。 不幸的是,沒有任何效果,我在許多論壇中都找不到任何可行的解決方案。 有誰知道這是怎么做到的嗎。
當我在沒有從“Usercontrol1”啟動的方法的情況下更改“Form1”中的標簽文本時,標簽的文本更改沒有任何問題。
你的做法是錯誤的。 將表單視為控件之間的中介,您通常不希望控件相互了解。 相反,您希望您的表單在您的控件之間編排操作和數據。
用戶控件1
public partial class UserControl1 : UserControl
{
// Setup an event to allow our Form to handle this controls button click.
// The Form containing this user control will need to attach a method to this event
public event EventHandler<EventArgs> ButtonClick = null;
public UserControl1()
{
InitializeComponent();
}
// handle this control's button1 Click event
private void button1_Click(object sender, EventArgs e)
{
ButtonClick?.Invoke(sender, e);
}
}
用戶控件2
public partial class UserControl2 : UserControl
{
public UserControl2()
{
InitializeComponent();
// map our InputTextBox property to TextBox on our control's UI
InputTextBox = textBox1;
}
// add a TextBox property that can be accessed outside of the control
public TextBox InputTextBox { get; }
}
表格1
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
// setup method to handle the UserControl1's ButtonClick event
private void userControl1_ButtonClick(object sender, EventArgs e)
{
// call the TextBox property on UserControl2 and set its Text value.
userControl2.InputTextBox.Text = "Test!";
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.