1

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 the 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 Behaviors is slightly different than this example). WebForms generates a parser error when I try to initialize the property in this way. The same question could be applied to other List types (int, strings).

Jason
  • 28,040
  • 10
  • 64
  • 64
  • I realize I could implement Behaviors as a string property and have a custom setter (that would split and initialize a private list), but I was wondering if there was a cleaner approach. – Jason May 13 '09 at 18:35

2 Answers2

1

After researching this further, I found that WebForms does use a TypeConverter if it can find it. The type or the property needs to be decorated properly, as detailed in this related question.

I wound up implementing 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);
            }
        }
    }
}
Community
  • 1
  • 1
Jason
  • 28,040
  • 10
  • 64
  • 64
0

Your own suggestion of a string property is the only solution when working with markup.

Ropstah
  • 17,538
  • 24
  • 120
  • 194
  • Do you know if WebForms queries the TypeConverters that have been registered? If not, then it appears that the string kludge is the only solution, like you said. – Jason May 13 '09 at 19:06