[英]Set custom properties using reflection on custom UserControl
我需要使用反射來設置自定義userControls的兩個自定義屬性
CustomUserControl.cs
......
public string _ValidaMsg { get { return _ValidarMsg; } set { _ValidarMsg = value; } }
public bool _Valida { get { return _Validar; } set { _Validar = value;} }
._Valida
確定在提交表單之前是否需要驗證控件, ._ValidaMsg
是字段未完成時顯示的消息
在我的form.cs中,我有一個名為listaMetodo (String ControlName,String ControlText,Type Control.Type)
的類型化列表listaMetodo (String ControlName,String ControlText,Type Control.Type)
這是填充列表的方法
private List<xEntidades.entControlValidacion> GetAllControls(Control container)
{
foreach (Control c in container.Controls)
{
GetAllControls(c);
// these txtDescripcion and others are the diferent types of my customs UserControls
if (c.Name.Equals("txtDescripcion") || c.Name.Equals("Combo") || c.Name.Equals("txtCodigo") || c.Name.Equals("txtFecha"))
{
listaMetodo.Add(new xEntidades.entControlValidacion(c.Parent.Name, c.Text, c.GetType()));
}
}
return listaMetodo;
}
因此,一旦有了包含所有相關控件的列表,我要做的就是將其與我擁有的列表進行比較,其中充滿了需要驗證的所有控件,我們稱其為validateList(string NameOfControl,bool Valida , String ValidaMsg)
。 在for循環中同時迭代兩個列表時,我有條件
If(listaMetodo[iExample].ControlName.equals(validateList[jExample].NameOfControl && validateList[jExample].Valida){
//here I should get the instance of the object by reflection and change ._ValidaMsg and ._Valida
}
因此,如何使用存儲在我的listaMetodo中的Type和ControlName修改實例對象的屬性?使用反射是強制性的嗎? 是否有另一個解決方案可以實現我的目標? 我也正在使用Framework 2.0預先感謝
好吧,最終我實現了我想要創建此方法的目標
private void validaControles()
{
for (int j = 0; j < listaMetodo.Count; j++)
{
for (int k = 0; k < listaControlesValida.Count; k++)
{
//just ignore this condition
if(listaMetodo[j].NombrePadre.Equals(listaControlesValida[k].Control) && listaControlesValida[k].Valida && listaMetodo[j].TextoControl.Equals("")){
listaControlesValida[k].ValidaText, null);
Control[] control = this.Controls.Find(listaMetodo[j].NombrePadre, true);
Type type = control[0].GetType();
control[0].GetType().GetProperty("_ValidaMsg").SetValue(control[0], listaControlesValida[k].ValidaText, null);
control[0].GetType().GetProperty("_Valida").SetValue(control[0], true, null);
}
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.