2
這裏我有一個使用ControlBuilder使DropDown控件通用的代碼。由ControlBuilder實現的通用DropDown丟失了所有屬性
[ControlBuilder(typeof(EnumDropDownControlBuilder))]
public class EnumDropDown : DropDownList {
private string _enumType;
private bool _allowEmpty;
public string EnumType {
get { return _EnumType; }
set { _EnumType = value; }
}
public bool AllowEmpty {
get { return _allowEmpty; }
set { _allowEmpty= value; }
}
}
public class EnumDropDown<T> : EnumDropDown where T : struct {
public EnumDropDown() {
this.Items.Clear();
if (AllowEmpty) this.Items.Add(new ListItem("", "__EMPTY__"));
foreach (string name in Enum.GetNames(typeof(T))) {
Items.Add(name);
}
}
public new T SelectedValue {
get {
if (IsEmpty) throw new NullReferenceException();
return (T)Enum.Parse(typeof(T), base.SelectedValue, true);
}
set { base.SelectedValue = Enum.GetName(typeof(T), value); }
}
public bool IsEmpty {
get {
return base.SelectedValue == "__EMPTY__";
}
set { base.SelectedValue = Enum.GetName(typeof(T), value); }
}
}
public class EnumDropDownControlBuilder : ControlBuilder {
public override void Init(TemplateParser parser, ControlBuilder parentBuilder, Type type, string tagName, string id, IDictionary attribs) {
string enumTypeName = (string)attribs["EnumType"];
Type enumType = Type.GetType(enumTypeName);
if (enumType == null) {
throw new Exception(string.Format("{0} cannot be found or is not an enumeration", enumTypeName));
}
Type dropDownType = typeof(EnumDropDown<>).MakeGenericType(enumType);
base.Init(parser, parentBuilder, dropDownType, tagName, id, attribs);
}
}
對不起,程序太長,不能愉快地閱讀。
的問題是,雖然我在類EnumDropDown定義的屬性EnumType,AllowEmpty。由於通過ControlBuilder創建的真正目的,就是EnumDropDown,EnumType,AllowEmpty的值總是空和假在控制對象。 在.aspx中設置的所有屬性都將丟失!
我可以讀取ControlBuilder中源標記的屬性值。 但我沒有任何想法如何將屬性複製到通用控制對象。
任何人都可以給我一些提示?