在UserControls之间传递CheckBox值

我试图将CheckBox值从UserControl3传递给UserControl1

在UserControl3上

public void materialCheckBox1_CheckedChanged(object sender, EventArgs e) { if (materialCheckBox1.Checked) { Environment.Exit(0) } else { //Nothing } } 

如何将值添加到UserControl1?

例如,单击UserControl1时的按钮将检查UserControl3上是否选中了复选框。

控件之间的通信有多种解决方案。

您已经在BindingNavigatorBindingource等控件之间的交互中看到了这样的function,其中BindingNavigator具有BindingSource类型的属性,每次单击导航按钮时, BindingNavigator调用BindingSource方法。

要自己实现它,例如在UserControl2您可以创建一个公共属性,公开您希望UserControl1能够检查的信息,然后在UserControl1 ,您应该具有UserControl2类型的属性。 这样,当您在设计时或运行时将UserControl2的实例分配给属性时,您可以使用公开的信息。

例如,按照以下步骤操作:

1)在UserControl2 ,公开您需要在控制之外使用的信息。

 public bool CheckBoxValue { get { return checkBox1.Checked; } set { checkBox1.Checked = value; } } 

2)在UserControl1 ,创建UserControl2类型的属性。 因此,您可以使用分配给它的实例并查找CheckBoxValue属性的值。

 public UserControl2 UserControl2Instance { get; set; } private void button1_Click(object sender, EventArgs e) { if(UserControl2Instance!=null) { if(UserControl2Instance.CheckBoxValue) MessageBox.Show("Checked"); else MessageBox.Show("Unchecked"); } } 

3)在表单上删除UserControl1UserControl2并使用设计器(或在运行时)将UserControl2的实例分配给UserControl2Instance属性。 然后,当您运行程序并单击UserControl1 Button1时,您可以看到位于UserControl2上的checkBox1的值。

与代表们合作!

要了解更多信息,请点击此处 ! 有关更多信息,请查看此msdn 文章 。