Is it possible to initialize the Control List <T> property in markup?
Let's say we have the following:
public enum RenderBehaviors
{
A,
B,
C,
}
public class MyControl : Control
{
public List<RenderBehaviors> Behaviors { get; set; }
protected override void Render(HtmlTextWriter writer)
{
// output different markup based on behaviors that are set
}
}
Is it possible to initialize the Behaviors property in ASPX / ASCX markup? i.e:.
<ns:MyControl runat="server" ID="ctl1" Behaviors="A,B,C" />
Subclassing is not an option in this case (the actual intent of the Behavior is slightly different from this example). WebForms throws a parser error when I try to initialize a property this way. The same question can be applied to other types of list (int, strings).
+1
a source to share
2 answers
After researching this, I found that WebForms does indeed use the TypeConverter if it can find it. The type or property needs to be styled correctly as described in this related question .
I started to implement something similar to this:
public class MyControl : Control
{
private readonly HashSet<RenderBehaviors> coll = new HashSet<RenderBehaviors>();
public IEnumerable<RenderBehaviors> Behaviors { get { return coll; } }
public string BehaviorsList
{
get { return string.Join(',', coll.Select(b => b.ToString()).ToArray()); }
set
{
coll.Clear();
foreach (var b in value.Split(',')
.Select(s => (RenderBehvaior)Enum.Parse(typeof(RenderBehavior), s)))
{
coll.Add(b);
}
}
}
}
+1
a source to share