Custom Controls with properties

Topics: Controls
Nov 27, 2007 at 12:39 AM
I'm interested in being able to add a custom control to posts and to pages. I'm happy to see that BlogEngine.Net already supports this. However, the control I want to add also needs to have some properties set on it. I see that as of 1.2, it doesn't look like there is any way to set these properties.

I'd like to propose that the CustomControl functionality be extended to support setting properties. I'm not sure exactly what format should be used to do so. I was playing around with something like this...


I went ahead and made a mod to my code that supports this. But I'd like to see what input other people would have on the subject. Perhaps a better way to describe how you wanted to set properties. In any case I'll include the code I wrote as a starting point for discussion. It currently only supports setting text properties, but could easily be extended to support more.

//anticipate sctrl in format '~/MyCtrl.ascx:Prop1=Val1;Prop2=val2'
public static Control CreateUserControl(TemplateControl parentControl, string sCtrl)
//create a dictionary to store desired property values, loop throu
Dictionary<string, string> dicProps = new Dictionary<string, string>();
string[] props = sCtrl.Split(':');
string sCtrlFile = props0; //control path in first element of array
for (int i = 1; i < props.Length; i++)
string prop = propsi;
int iSeparator = prop.IndexOf("=");
if (iSeparator > -1)
dicProps.Add(prop.Substring(0, iSeparator), prop.Substring(iSeparator + 1));

//create the control
Control retval = parentControl.LoadControl(sCtrlFile);

//loop through properties dictionary and set each.
foreach (string propname in dicProps.Keys)
Type t = retval.GetType();
System.Reflection.PropertyInfo pInfo = t.GetProperty(propname);
if (pInfo == null)
throw new Exception(string.Format("{0} does not have a property {1}", t.Name, propname));

//return the control with the properties set.
return retval;

then replace the code where the control is normally loaded with the following (example, in postviewbase.cs)

Control customCtrl = BlogEngine.Core.CustomControlLoader.CreateUserControl(this, myMatch.Groups1.Value);

Let me know what you think everyone!

Eric Oldre

PS. is there a way with this discussion board to have it format code snippets nicely? I apologize for the look of the above. :)