I\'ve created a user control with some buttons. When you click a button in the UserControl the BackColor of the button changes:
private void button1(object send
i fixed it like this;
control:
public delegate void ColorChangeEventHandler();
public partial class myControl: UserControl
{
public event ColorChangeEventHandler ColorChanged;
private void OnColorChange()
{
if(ColorChanged != null)
{
ColorChanged.Invoke();
}
}
public speelRij()
{
InitializeComponent();
}
private void Button1_Click(object sender, EventArgs e)
{
OnColorChange();
Control ctrl = ((Control)sender);
switch (ctrl.BackColor.Name)
{
case "Crimson": ctrl.BackColor = Color.Blue; break;
case "Green": ctrl.BackColor = Color.Orange; break;
case "Orange": ctrl.BackColor = Color.Crimson; break;
case "Blue": ctrl.BackColor = Color.Green; break;
default: ctrl.BackColor = Color.Crimson; break;
}
form:
public myForm()
{
InitializeComponent();
myControl1.ColorChanged += () => { Button1.Enabled = true;};
}
You can get a reference to the parent form using this
Form parentFrm = (this.Parent as Form);
You can then access controls on the parent Form, by either making the public or finding the control by its name
Button aButton = (Button)parentFrm.Controls["btnName"];
if (aButton != null)
aButton.Enabled = true;
you can use Event Aggregator and make the button in user control will publish an event and make you window handle the event
In your UserControl
make event handler ColorChanged
and fire that event when color changes. In your form add listener and appropriate code when event fires.
So, in your control, make EventHandler
, like this
public partial class UserControl1 : UserControl
{
public EventHandler ColorChanged;
then, fire event on your button click, like this:
private void button1(object sender, EventArgs e)
{
ColorChanged?.Invoke(sender, e);
//rest of your code...
}
in your form, add listener:
userControl.ColorChanged += new EventHandler(UserControl_ColorChanged)
and add method that will be executed and enable button...
private void UserControl_ColorChanged(object sender, EventArgs e)
{
//enable button here
}