C# 使用'对所有控件执行操作;ImageUrl';财产
下面是一段代码,它遍历网页上的控件,其中是imagebutton,它修改imageUrl属性。我想让它做的是,检查每个控件,如果该控件碰巧有imageUrl属性,那么进行更改。例如,正常图像等将包括在该过程中。我有种感觉,泛型或其他东西可能是这里的关键,但至少可以说,我在这方面还不精通。有什么想法吗?谢谢C# 使用'对所有控件执行操作;ImageUrl';财产,c#,asp.net,C#,Asp.net,下面是一段代码,它遍历网页上的控件,其中是imagebutton,它修改imageUrl属性。我想让它做的是,检查每个控件,如果该控件碰巧有imageUrl属性,那么进行更改。例如,正常图像等将包括在该过程中。我有种感觉,泛型或其他东西可能是这里的关键,但至少可以说,我在这方面还不精通。有什么想法吗?谢谢 public static void AddThemePathToImages(Control Parent) { foreach (Control
public static void AddThemePathToImages(Control Parent)
{
foreach (Control c in Parent.Controls)
{
ImageButton i = c as ImageButton;
if (i != null)
{
// See if theme specific version of this file exists. If not, point it to normal images dir.
if (File.Exists(System.Web.HttpContext.Current.Server.MapPath("~/App_Variants/" + GetUserTheme().ToString() + "/images/" + i.ImageUrl)))
{
i.ImageUrl = "~/App_Variants/" + GetUserTheme().ToString() + "/images/" + i.ImageUrl;
}
else
{
i.ImageUrl = "~/images/" + i.ImageUrl;
}
}
if (c.HasControls())
{
AddThemePathToImages(c);
}
}
}
如果没有设置属性,那么我认为imageUrl将为null或空字符串。试着把它放在“如果”语句中。我认为这将解决您的问题。您不需要泛型,只需常规继承即可: 由于只是从其父类的继承,您只需将第一位更改为:
ImageButton i = c as ImageButton;
致:
然后它可以很好地用于Image和ImageButton
现在,如果您希望它用于任何具有Image EURL属性的控件(甚至是一些不从图像派生的自定义控件),那么您需要使用反射来查看对象是否具有Image Eull属性,如果是,请使用它。
< P>我将考虑创建一个子类自定义控件<强>“MeimDimeBut纽”。可以封装用于在每个图像上设置正确ImageUrl的代码 可以添加覆盖OnPreRender以检查图像是否存在并更新属性 然后,您可以通过要替换的项目执行简单的查找和替换您也可以为控件提供相同的解决方案。太好了,效果非常好!我并没有从遗传的角度考虑这个问题——你只是刺激了一些新的神经联系……:)最好是用一个很好的图形表示从什么继承下来的东西……谢谢你,这确实是一个可行的方法,尽管对每个相关控件重复它促使我朝着James提供的解决方案前进。非常感谢华莱士!
Image i = c as Image;
public class ThemedImageButton : ImageButton
{
protected override OnPreRender(EventArgs e)
{
// See if theme specific version of this file exists. If not, point it to normal images dir.
if (File.Exists(System.Web.HttpContext.Current.Server.MapPath("~/App_Variants/" + GetUserTheme().ToString() + "/images/" + i.ImageUrl)))
{
i.ImageUrl = "~/App_Variants/" + GetUserTheme().ToString() + "/images/" + i.ImageUrl;
}
else
{
i.ImageUrl = "~/images/" + i.ImageUrl;
}
}
}