marți, 24 noiembrie 2009

[C#] [GUI] Dynamically loading a user control

Dynamically loading a user control:
1. Create the control.
2. Add the control to the form’s Controls collection.
3. register any event for that control
4. Set the control’s properties for size/position.
5. Make the control visible (Visible = true).
6. Set the control’s z-order (BringToFront()).

public partial class MyUserControl : UserControl {...};
UserControl m_Ctrl = new MyUserControl();
m_partCtrl.OnClosed += new EventHandler(CloseUserControl);
m_Ctrl.Dock = DockStyle.Fill;
m_Ctrl.Visible = true;
this.Text = "Focused window - " + m_Ctrl.ToString();

Removing User Controls
private void CloseUserControl(object sender, EventArgs e)
MyUserControl _Ctrl= (MyUserControl)sender;
_Ctrl.CloseWinPart -= new EventHandler(CloseUserControl);
_Ctrl.Visible = false;
this.Text = "Main Form";

!!! - failing to unhook events can cause memory leaks

Niciun comentariu:

Trimiteți un comentariu