在表单上的用户控件之间进行通信

本文关键字:之间 通信 控件 用户 表单 | 更新日期: 2023-09-27 18:02:46

我想调用usercontrol函数/方法从另一个按钮点击时,我的用户控制父是表单…

形式;加载并添加用户控件:

//Controls enum holding names of all our user controls
public enum ControlsEnum
{
    SPLASH_CONTROL,
    MAIN_CONTROL,
    CATEGORY_CONTROL,
}
public partial class MainForm : Form
{
    //Dictionary that holds all our instantiated user controls.
    private IDictionary<ControlsEnum, Control> controls = new Dictionary<ControlsEnum, Control>();
    public MainForm()
    {
        InitializeComponent();
        //When the program runs for the first time, lets call the ShowControl method that
        //will show the first control
        ShowControl(ControlsEnum.SPLASH_CONTROL);
    }
    public void ShowControl(ControlsEnum ctrl)
    {
        Control new_ctrl = null;
        //If our dictionary already contains instance of
        if (controls.ContainsKey(ctrl))
        {
            new_ctrl = controls[ctrl];
        }
        else
        {
            new_ctrl = CreateControl(ctrl);
            controls[ctrl] = new_ctrl;
        }
        new_ctrl.Parent = this;
        new_ctrl.Dock = DockStyle.Fill;
        new_ctrl.BringToFront();
        new_ctrl.Show();
    }
    private Control CreateControl(ControlsEnum ctrl)
    {
        switch (ctrl)
        {
            case ControlsEnum.SPLASH_CONTROL:
                return new Splash_uc();
            case ControlsEnum.MAIN_CONTROL:
                return new Main_uc();
            case ControlsEnum.CATEGORY_CONTROL:
                return new Categoty_uc();
            default:
                return null;
        }
    }

and

private void btn_categorySave_Click(object sender, EventArgs e)
{
   // i want refresh datagridview and add new category to list by save in database
}

and in main_uc:

private void datagridview_Refresh()
{
  //rebind datagridview datasource
  // i want call this function from "category_uc" when click on Save Button
}

请帮帮我!tnx;

在表单上的用户控件之间进行通信

您可以为控件添加一个事件:

class Categoty_uc
{
  public event EventHandler ButtonClicked;
  protected OnButtonClicked()
  {
    var tmp = ButtonClicked;
    if(tmp != null)
    {
      tmp(this, EventArgs.Empty);
    }
  }
  private void btn_categorySave_Click(object sender, EventArgs e)
  {
    OnButtonClicked();
  }
}

然后在主表单中:

private Main_uc main_uc = null;
private Control CreateControl(ControlsEnum ctrl)
{
  Control ret = null;
  switch (ctrl)
  {
    case ControlsEnum.CATEGORY_CONTROL:
    {
      if(main_uc != null)
      {
        ret = new Categoty_uc();
        ((Categoty_uc)ret).ButtonClicked += (sender, e) => 
                          {main_uc.datagridview_Refresh();}
      }
      else
      {
        throw new Exception("Create Main_uc first!");
      }
    }
    break;
    case ControlsEnum.MAIN_CONTROL:
    {
      if(main_uc == null)
      {
        main_uc = new Main_uc();
      }
      ret = main_uc;
    }
  }
  return ret;
}