Tuesday, 8 September 2009

Design Time Stylesheets for User Controls

Some people can be slightly pedantic when it comes to writing code and would like to have the utopian idea of a build with zero errors and zero warnings. I'm definately on this spectrum.

Visual Studio doesn't make this easy for you in some circumstances. Styling and Theming has had some excellent advancements in the last couple of iterations of the Visual Studio environment but how do you get round the issue of design time css warnings? You don't want to add the stylesheet to every control as it will output to the page in runtime but if you don't add it the VS doesn't know about it and can't validate your class names.

Well the first option is to turn off the warnings. This I wouldn't call elegant as you are then missing out on part of the validation process and the warnings can be used to your benefit. To do this click Tools -> Options. Expand the Text Editor item, then HTML, then Validation. Untick the 'as warnings (HTML, CSS)'. This plasters over the cracks which might be enough for you. But eventually the cracks will widen and it would have been really useful to see into the crack and find out what was pushing it wider.

The most elegant way is to take advange of Visual Studios rendering architecture. This code shows you how, those eagle eye'd among you will see the solution straight away.
<link href="mainStyle.css" rel="stylesheet" type="text/css" runat="server" id="lnkcss" visible="false" />

Link in the stylesheet to the user control and add the runat, id and then the attribute which makes all this worth while the visible="false". Using the visible=false the rendering engine will not output any part of the tag and then you've made a design time stylesheet. As the style sheet has no state management and no events there would only be a marginal increase to the memory usage for the site. And if you're that bothered about memory management then shut up and refactor your code again.

I'm not saying this is a solution for every situation but if the shoe fits....

No comments: