是否可以初始化控件的List< T>.标记中的属性? [英] Is it possible to initialize a Control's List<T> property in markup?
问题描述
假设我们有以下内容:
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
}
}
是否可以在ASPX/ASCX标记中初始化Behaviors属性?即:
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" />
在这种情况下,
子类化不是一个选项(行为"的实际意图与该示例略有不同).当我尝试以这种方式初始化属性时,WebForms会生成解析器错误.相同的问题可以应用于其他List类型(int,字符串).
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).
推荐答案
进一步研究之后,我发现WebForms确实可以使用TypeConverter.类型或属性需要正确修饰,如此相关问题.
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.
我结束了类似的事情:
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);
}
}
}
}
这篇关于是否可以初始化控件的List< T>.标记中的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!