[英]Add attributes to a control class
I wanna know if it is possible to add attribute to a Control
in c#. 我想知道是否可以在c#中向
Control
添加属性。
I have a method it receive an object in parameter : 我有一个方法在参数中接收对象:
public void CreateTooltip(Object controltoadd = null)
{
var myDiv = new HtmlGenericControl("div");
myDiv.Attributes.Add("width", "100%");
myDiv.Attributes.Add("onmouseover", "ShowHint('" + this.GetType() + "','test');");
myDiv.Attributes.Add("onmouseout", "HideHint();");
if (controltoadd == null)
{
List<Control> listcc = new List<Control>();
for (int i = 0; i < this.Controls.Count; i++)
{
Control cc = this.Controls[i];
string test = cc.GetType().ToString();
listcc.Add(cc);
}
this.Controls.Clear();
for (int i = 0; i < listcc.Count; i++)
{
Control cc = listcc[i];
myDiv.Controls.Add(cc);
}
}
else
{
Control cc = (Control)controltoadd;
//Don't know what to do here...
}
this.Controls.Add(myDiv);
}
If the object is null, I create a HtmlGenericControl("div")
and then I add the Attributes
I want. 如果对象为null,则创建一个
HtmlGenericControl("div")
,然后添加所需的Attributes
。 But the problem is when the Object is not null, I convert it to Control
, and the property Attributes
is not available. 但是问题是当Object不为null时,我将其转换为
Control
,并且属性Attributes
不可用。 I use control because I never know which is the type of the object I received in the parameter. 我使用控件是因为我永远不知道参数中接收到的对象是哪种类型。
You need to cast it as a WebControl
or a HtmlGenericControl
I believe. 我相信您需要将其转换为
WebControl
或HtmlGenericControl
。 Control
does not contain the property Attributes
. Control
不包含属性Attributes
。 You can test what the object you pass is by using is
. 您可以使用来测试传递的对象
is
。
if (control is WebControl)
{
var webControl = (WebControl)control;
}
Or if you prefer to use as
: 或者,如果您更喜欢
as
:
var webControl = control as WebControl;
if (webcontrol != null)
{
// code
}
So if it's actually a WebControl
(child-class of Control
) then you can cast it to it and use it's Attributes
property . 因此,如果它实际上是
WebControl
( Control
子类),则可以将其强制转换为它并使用它的Attributes
属性 。 Control
itself has no property Attributes
as you've already noticed: 您已经注意到,
Control
本身没有属性Attributes
:
WebControl wc = controltoadd as WebControl;
if(wc != null)
{
// wc.Attributes.Add...
}
If it's a HtmlControl
cast it to that: 如果是
HtmlControl
则将其HtmlControl
转换为:
else
{
HtmlControl hc = controltoadd as HtmlControl;
if(hc != null)
{
// hc.Attributes.Add...
}
}
Another option would be to make it a generic method that accepts only controls that implement IAttributeAccessor
. 另一种选择是使它成为仅接受实现
IAttributeAccessor
控件的通用方法。 Both, HtmlControl
and WebControl
implement that interface to get/set attributes.: HtmlControl
和WebControl
实现该接口以获取/设置属性。
public void CreateTooltip<T>(T controlToAdd)where T: IAttributeAccessor, Control
{
// ....
controlToAdd.SetAttribute("width", "100%");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.