2

我以前在中继器中完成过这项任务并且它已经奏效了。但是,我无法在正常的网络表单页面中为我工作。图像显示为断开的链接,并且我在代码隐藏中放置的断点没有被触发。

(在 aspx 文件中)

<asp:ImageButton ID="ImageButton1" runat="server" ImageUrl='<%# GetImageDirectory()%>btnRunReport.png'  />

(代码隐藏)

public string GetImageDirectory()
{
    return "~/App_Variants/LBSX/images/";
}

这是我尝试过的第二种方法,在另一种方法中,我尝试将图像名作为字符串传递,它会以这种方式返回整个链接。还是没有运气!

有什么想法吗?

谢谢!

[编辑] 感谢大家的帮助。最后,在方便的提示之后,我找到了一个递归片段,它的技巧如下:

private void UpdateImages(Control Parent)
{
    foreach (Control c in Parent.Controls)
    {
        ImageButton i = c as ImageButton;
        if (i != null)
        {
            i.ImageUrl = "~/App_Variants/LBSX/images/" + i.ImageUrl;
        }
        if (c.HasControls())
        {
            UpdateImages(c);
        }
    }
}

protected void Page_Load(object sender, EventArgs e)
{
    UpdateImages(Page);
    ...

希望它可以帮助别人。

干杯

4

3 回答 3

6

首先,就像 Zachary 提到的,您正在使用代码块进行数据绑定。

其次,正如您已经尝试过的那样,<%= %>在您的情况下使用内联表达式 ( ) 也不起作用,因为您不能对服务器标签的任何属性使用内联表达式。

您可以做的是使用 HTML 语法定义图像按钮,省略runat="server"标记,并使用内联表达式获取图像的 URL:

<input type="image" src="<%= GetImageDirectory() %>btnRunReport.png" name="image" />

内联表达式的作用是,它Response.Write()以 between 的值<%= %>作为参数调用,例如<%= this.MyVar %>is Response.Write(this.MyVar)

于 2010-07-19T07:04:00.723 回答
2

您的语法用于数据绑定,<%# %>。如果你只是想做内联 c#,你应该使用 <%= %>。

于 2010-07-19T05:37:52.043 回答
1

我给你另一个解决方案。使用ExpressionBuilder

  1. 创建从 ExpressionBuilder 派生的类并覆盖函数 GetCodeExpression

     namespace your.namespace
    {
    public class CustomBuilder : ExpressionBuilder
    {
        public override CodeExpression GetCodeExpression(BoundPropertyEntry entry, object parsedData, ExpressionBuilderContext context)
        {
            Type type1 = entry.DeclaringType;
            PropertyDescriptor descriptor1 = TypeDescriptor.GetProperties(type1)[entry.PropertyInfo.Name];
            CodeExpression[] expressionArray1 = new CodeExpression[1];
            expressionArray1[0] = new CodePrimitiveExpression(entry.Expression.Trim());
    
            String temp = entry.Expression;
            return new CodeCastExpression(descriptor1.PropertyType, new CodeMethodInvokeExpression(new
           CodeTypeReferenceExpression(base.GetType()), "GenerateLink", expressionArray1));
        }
        public static  String GenerateLink(String link)
        {
            return ConfigurationManager.AppSettings["MediaPath"] + link + "?ver=" + ConfigurationManager.AppSettings["MediaCode"];
        }
    }
    }
    

expressionArray1GenerateLink函数的输入数组。您可以根据函数的输入参数数量更改数组的大小

2.在webconfig中注册你的表达式

<system.web>
    <compilation debug="true" targetFramework="4.0" >
      <expressionBuilders>

        <add expressionPrefix="GenLink" type="your.namespace.CustomBuilder"/>
      </expressionBuilders>

    </compilation>

3.鉴于您可以使用新的表达方式:

<asp:ImageButton ID="ImageButton1" runat="Server" ImageUrl='<%$ GenLink:images/magnifier.jpg %>'/>

4.享受!!!

于 2014-01-08T10:21:19.173 回答