Call a button on a C# form through usercontrol

后端 未结 4 2157
广开言路
广开言路 2021-01-23 18:37

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         


        
相关标签:
4条回答
  • 2021-01-23 18:49

    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;};
        }
    
    0 讨论(0)
  • 2021-01-23 18:51

    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;
    
    0 讨论(0)
  • 2021-01-23 18:51

    you can use Event Aggregator and make the button in user control will publish an event and make you window handle the event

    0 讨论(0)
  • 2021-01-23 19:04

    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
    }
    
    0 讨论(0)
提交回复
热议问题