[英]Copy css from one control to another control
我在aspx页面上有多个图像控件。 我分配一些CSS如下
control1.Style.Add("position", "relative");
...
...
取决于一些计算。
现在我想要在其他控件上复制相同的样式,例如control2
//something like
control2.Style=control1.Style;
//not possible since it has no setter
所以还有另一种方式可以做到
control2=control1;
它将把control1内部的所有属性复制到控件2。我认为这是不可能的。 所以有什么办法可以做到这一点。
当我写
control2=control1;
所有的css从control1复制到control2(在我的情况下,它们都是相同的类型)。 但是天气会改变其他情况吗?
我认为没有直接的方法可以做到这一点。 但是您可以创建这样的扩展方法。
public static class StyleExtension
{
public static void AddExisting(this CssStyleCollection collection,
CssStyleCollection existing)
{
foreach (string item in existing.Keys)
{
collection.Add(item, existing[item]);
}
}
}
您可以像这样使用它。
cmdSubmit.Style.Add("Color", "Red");
cmdSubmit.Style.Add("FontSize", "20");
Button1.Style.AddExisting(cmdSubmit.Style);
您的问题回答了一些论坛HERE
他们编写了一个克隆控件的函数。
为了遵守stackoverflow的规则,我在下面的答案中添加了代码:
/// <summary>
/// The ControlCloneEngine creates copies of ASP.NET controls
/// </summary>
public class ControlCloneEngine
{
private int m_instanceCount;
public ControlCloneEngine()
{
m_instanceCount = 1;
}
/// <summary>
/// Clone a control. Call this function in Page_Init
/// </summary>
/// <param name="ctrlSource">The control to clone</param>
/// <returns>a new copy of the control</returns>
public Control Copy(Control ctrlSource)
{
Type t = ctrlSource.GetType();
Control ctrlDest = (Control)t.InvokeMember("", BindingFlags.CreateInstance, null, null, null);
foreach (PropertyInfo prop in t.GetProperties())
{
if (prop.CanWrite)
{
if (prop.Name == "ID")
{
ctrlDest.ID = ctrlSource.ID + "c" + m_instanceCount;
}
else
{
prop.SetValue(ctrlDest, prop.GetValue(ctrlSource, null), null);
}
}
}
m_instanceCount++;
return ctrlDest;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.