在用户控件之间传递复选框值 [英] Passing CheckBox Values between UserControls
问题描述
我试图将CheckBox值从UserControl3传递给UserControl1
I am trying to pass a CheckBox value from UserControl3 to UserControl1
在UserControl3上
On UserControl3
public void materialCheckBox1_CheckedChanged(object sender, EventArgs e)
{
if (materialCheckBox1.Checked)
{
Environment.Exit(0)
}
else
{
//Nothing
}
}
如何将值添加到UserControl1?
How would I add the value to UserControl1?
例如,单击时的按钮UserControl1将检查UserControl3上的复选框是否已选中。
For example a button when clicked on UserControl1 will check if the checkbox is checked on UserControl3.
推荐答案
控件之间的通信有多种解决方案。
There are multiple solutions for communication between controls.
您已经看到 BindingNavigator
和 Bindingource
,其中 BindingNavigator
具有类型为 BindingSource
的属性,并且每次单击导航按钮时, BindingNavigator
调用 BindingSource
的方法。
You have seen such functionality in interaction between controls like BindingNavigator
and Bindingource
where the BindingNavigator
has a property of type BindingSource
and each time you click on navigation buttons, the BindingNavigator
calls methods of BindingSource
.
为其实现您自己,例如在 UserControl2
中,您可以创建一个公共属性,以公开您希望 UserControl1
能够检查的信息。 ,然后在 UserControl1
中,您应该具有 UserControl2
类型的属性。这样,当您在设计时或运行时将 UserControl2
的实例分配给属性时,便可以使用公开的信息。
To implemenet it for yourself, for example in UserControl2
you can create a public property exposing the information which you want the UserControl1
be able to check, then in the UserControl1
, you should have a property of type of UserControl2
. This way when you assign the instance of UserControl2
to the property at design-time or run-time, then you can use exposed information.
例如,请按照下列步骤操作:
For example follow these steps:
1)在您的 UserControl2
中,公开
public bool CheckBoxValue
{
get { return checkBox1.Checked; }
set { checkBox1.Checked = value; }
}
2)在您的 UserControl1 $ c中$ c>,创建一个类型为
UserControl2
的属性。因此,您可以使用分配给它的实例并找到 CheckBoxValue
属性的值。
2) In your UserControl1
, create a property of type UserControl2
. So you can use the instance which is assigned to it and find the value of CheckBoxValue
property.
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)都删除 UserControl1
和 UserControl2
在表单上并使用设计器(或在运行时)分配 UserControl2 $ c的实例$ c>到
,位于 UserControl1
的 UserControl2Instance
属性。然后,当您运行程序并单击 UserControl1
中的 Button1
时,您会看到<$ c $的值c> checkBox1 UserControl2
。
3) Drop both UserControl1
and UserControl2
on the form and using designer (or at run-time) assign the instance of UserControl2
to UserControl2Instance
property of UserControl1
. Then when you run the program and click on Button1
of your UserControl1
, you can see the value of checkBox1
which is located on UserControl2
.
这篇关于在用户控件之间传递复选框值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!