Sometimes it’s necessary to access a method/property on a Page from the UserControl code.
Eg.
We have a Page that has a label on it. A UserControl is embedded in that page. The UserControl has a DropDownList of values. When the value in the DropDownList is changed, we want the UserControl to change the value of Page’s label to reflect the selected value of the drop down list.
Now because the UserControl is associated with the Page using aggregation and there is no reference back to the Page instance it becomes a little tricky to do this.
We could pass a reference to the label in the UserControl but once we do that, we are creating a tighter coupling between the Page and UserControl thus making it difficult to re-use the UserControl for Pages that don’t have a label that needs modification.
Don’t worry though! The Event Handler (or Observer) pattern is very handy and comes into play to enable a communication mechanism that gets around the coupling problem.
In the UserControl declare a public property that accepts and returns an EventHandler delegate.
Eg.
public class ExampleUserControl : UserControl {
protected DropDownList automobileTypes;
private EventHandler automobileChangeHandler;
public EventHandler AutomobileChangeHandler {
get { return automobileChangeHandler; }
set { automobileChangeHandler = value; }
}
Now call the declared EventHandler at the appropriate execution point.
Eg.
...
...
private void InitializeComponent() {
this.Load += new System.EventHandler(this.Page_Load);
automobileTypes.SelectedIndexChanged += new EventHandler(automobileTypes_SelectedIndexChanged);
}
private void automobileTypes_SelectedIndexChanged(object sender, EventArgs e) {
if (AutomobileChangeHandler != null) {
AutomobileChangeHandler(automobileTypes.SelectedValue, e);
}
}
In the Page class create a method to be executed by the UserControl’s event handler. Define the logic that the UserControl’s event is to trigger on the Page object.
Eg.
public class ExamplePage : Page {
protected Label name;
protected ExampleUserControl euc;
private void ExampleUserControl_Changed(object sender, EventArgs e) {
name.Text = String.Format("You have selected - {0}", sender as string);
}
override protected void OnInit(EventArgs e) {
InitializeComponent();
base.OnInit(e);
}
private void InitializeComponent() {
this.Load += new System.EventHandler(this.Page_Load);
euc.AutomobileChangeHandler += new EventHandler(ExampleUserControl_Changed);
}
#endregion
}
Thus allowing a UserControl to trigger events in the page object, without explicitly knowing about the class in which the UserControl resides.