Reputation: 1403
Here is my first experience creating a custom control. My real example is much larger, but this is boiled down for clarity. Ultimately, I need to hide as many properties of the custom control as possible so that when I share my new control with the rest of my team, they need only worry about the few properties that are required.
I have a control called TimeNow which inherits System.Web.UI.WebControls.Literal
and basically just prints the current time on the web page:
public class TimeNow : Literal
// Set to private so Text is hidden from the editor.
private string Text
{
get;
set;
}
protected override void Render(HtmlTextWriter writer)
{
// Get and write the time of now.
}
This works, but it seems clunky. I no longer see Text available in intellisense when I drop the control on a web page, but I do receive a warning that my Text is hiding the inherited Text. Is there a better way to hide the Text property?
Upvotes: 1
Views: 246
Reputation: 7915
I think you're doing something wrong if you derive from a Literal
that behaves like an ITextControl
(Literal has implemented this Interface) and then you try to remove the essential Text property? This is like deriving from cat but don't want to let them do "meow" and force them flying like a duck. You are searching for the Animal class instead, I think.
I don't know much about ASP.NET (only .Net for the Desktop). Maybe it is possible to use composition instead of inheritance (if you not really need the Literal -> "Cat") and you can inherit from System.Web.UI.Control
(-> "Animal") instead.
public class TimeNow : System.Web.UI.Control
{
// no need to do something here with the Text property, is not defined
}
or with composition
public class TimeNow : System.Web.UI.Control
{
private readonly Literal literal;
public TimeNow()
{
this.literal = new Literal();
// ... and set the Text etc., no one else can access
}
// or something like this
public TimeNow(ILiteralFactory literalFactory)
{
// the factory is just an example... don't know your context but this way your newly created literal can't be accessed
this.literal = literalFactory.CreateNewLiteral();
// do what you want with the text control, e.g. store internally
// Clone() the Literal etc.
// the
}
}
Update: Had a very quick look into the MSDN and maybe a Content Control is the thing you are looking for, instead of the Literal. (sorry if wrong, writing Desktop Apps)
Upvotes: 0
Reputation: 1542
Try this:
[Browsable(false)]
[EditorBrowsable(EditorBrowsableState.Never)]
private string Text
{
}
Upvotes: 0
Reputation: 24459
There should be more to that warning message, suggesting you use the new
keyword if you really intend to hide the inherited member, do what it says:
public class TimeNow : Literal
{
new private string Text
{
get;
set;
}
}
Upvotes: 1