2 个UserControl 的传值问题
问题描述:有2个UserControl:UserControl1 里有一个Button,UserControl2 里面有一个TextBox,这2个控件都加载到了主窗体Form1 上。要求的是,点击 UserControl1 的button 显示 UserControl2中TextBox输入的内容。
一般来讲有2种方式:
1. 公开属性
2. 声明事件
来看看这2种方式的操作代码:
1. 公开2个UserControl的属性。并在Form1中使用
public partial class UserControl1 : UserControl { public UserControl1() { InitializeComponent(); } public Button Btn // Define Btn as public { get { return this.button1; } } }
public partial class UserControl2 : UserControl { public UserControl2() { InitializeComponent(); } public TextBox textbox // define textbox as public { get { return this.textBox1; } } }
在From1中注册Button的事件
public partial class Form1 : Form { public Form1() { InitializeComponent(); this.userControl11.Btn.Click += new EventHandler(Btn_Click); } void Btn_Click(object sender, EventArgs e) { MessageBox.Show(this.userControl21.textbox.Text); } }
2. 声明事件
public partial class UserControl1 : UserControl { public UserControl1() { InitializeComponent(); } public event EventHandler BtnClick; //define one public Click event. private void button1_Click(object sender, EventArgs e) { BtnClick(sender, e); // just do it. } }
public partial class UserControl2 : UserControl { public UserControl2() { InitializeComponent(); } public event Action<string> GetText; //define one action to get textbox's text value private void textBox1_TextChanged(object sender, EventArgs e) { GetText(textBox1.Text); // Get this text after input. } }
在Form1中调用
public partial class Form1 : Form { public Form1() { InitializeComponent(); this.userControl21.GetText += new Action<string>(userControl21_GetText); // register gettext event. this.userControl11.BtnClick += new EventHandler(userControl11_Click); // Register Click event. } string text = null; void userControl11_Click(object sender, EventArgs e) // implement it { MessageBox.Show(text); } void userControl21_GetText(string obj) // implement it. { text = obj; } }