Reputation: 4809
I have 5 user controls on the page and each control implements it's own interface that contains properties and events. In order to enable communication between user controls, I am creating a property of target user control inside other user control. Through this property, it's state can be altered and be able to register its events.
Below is the pseudo code of results user control. It subscribes to OnSearch event of Search user control.
public interface IResults
{
//other fields
ISearch SearchControl { get;}
}
public partial class Results : IResults
{
//other fields
public ISearch SearchControl
{
get{
this.Page.Parent.FindControl("UCSearch") as ISearch;}
}
protected override void Page_Load(object sender, EventArgs e)
{
this.SearchControl.OnSearch += new EventHandler(testMethod);
}
}
Is it ok to have the reference properties inside user controls to subscribe to the events and manipulating the state. Does it create any maintenance problem in future.
Does FindControl and type casting degrade the performance of the application.
Upvotes: 1
Views: 150
Reputation: 11476
1) It's OK to register events from one object from inside another object. That's what they are for. :D
2) There would be a small amount of overhead involved performing the search each time SearchControl
in accessed. I doubt it would be of any significance, depending, of course, how frequently SearchControl
is called.
However, how you have implemented SearchControl
will present some maintenance problems in the future. By violating the Law of Demeter in SearchControl
you have tightly coupled your code to a Page
class that has a control named "UCSearch"
.
Instead why don't you include the a set accessor for the SearchControl
property, and have the parent provide the value of SearchControl
. Not only would this make the the code easier to maintain, but it is more loosely coupled, and also avoids your performance concerns! As an added bonus it will be easy to create unit test for!!!
public interface IResults
{
//other fields
ISearch SearchControl { get; set; }
}
public partial class Results : IResults
{
//other fields
private ISearch searchControl;
public ISearch SearchControl
{
get
{
return this.searchControl;
}
set
{
if (this.SearchControl != null)
{
this.SearchControl.OnSearch -= new EventHandler(testMethod);
}
this.searchControl = value;
this.SearchControl.OnSearch += new EventHandler(testMethod);
}
}
}
Upvotes: 1