[英]Communicate between usercontrols on form
當我的用戶控件父級為窗體時,我想通過按鈕單擊從另一個調用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;
}
}
並在Category_uc中:
private void btn_categorySave_Click(object sender, EventArgs e)
{
// i want refresh datagridview and add new category to list by save in database
}
並在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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.