views:

401

answers:

2

Hello, I am wanting to do custom rendering of the CSS styling, as such I created a new UserControl.

From there, I thought it'd be easy just create a new CssStyleCollection under the name Style. It does not work though! How do I make this code compile? (just an example)

class MyControl : UserControl{
  CssStyleCollection Style=new CssStyleCollection(); //compiler error on the `new..` 
}

I don't understand what I am doing wrong here. CssStyleCollection is a sealed class, but it is not static. How do I instantiate a new one!?

Also, the compiler error given is

The type System.Web.UI.CssStyleCollection has no constructors defined

A: 

Ok, technically the only proper way is to hack .Net and use reflection to call it's private constructor... see http://bart-at-work.blogspot.com/2008/11/create-cssstylecollection-instance.html

Well, I figure that a CssStyleCollection doesn't have anything too special in it, so what I did was a simple yet elegant hack without reflection.

CssStyleCollection Style=new Panel().Style;

I'm not sure how "safe" it is, but it works on .Net and Mono, so it's good enough for me.

Earlz
It's never proper to use private reflection to instantiate a type.
Eilon
It didn't feel right to me either, thats why I did the `new Panel().Style` thing.. The reflection thing is the only way I found to do it when googling though
Earlz
+2  A: 

Hey,

CssStyleCollection is created from a Style object; a Style object has a GetStyleAttributes method that returns a CssStyleCollection, so create a Style object, assign all the props you want, and return CssStyleCollection. Also, it requries IUrlResolutionService, which is a reference to the page or a control.

Brian
Reference to MSDN - http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.style.getstyleattributes%28v=VS.100%29.aspxSystem.Web.UI.WebControls.Style style = new System.Web.UI.WebControls.Style();CssStyleCollection cssStyles = style.GetStyleAttributes(someControl);
Daniel Ballinger