Mec*_*h0z 4 asp.net data-binding
我正在尝试为我的ASP.NET代码创建本地化,但是我在设置TemplateField的HeaderText时遇到了问题
我有这个有效
<asp:TemplateField HeaderText="Description">
<ItemTemplate>
<%# Eval("Description") %>
</ItemTemplate>
<FooterTemplate>
<asp:Panel ID="Panel5" runat="server" DefaultButton="EditSubmission">
<asp:TextBox runat="server" ID="Submission_DescriptionTxtBox" TextMode="MultiLine"
ToolTip='<%# GetById("atforbedringsforslag_description_tooltip") %>'/>
</asp:Panel>
</FooterTemplate>
</asp:TemplateField>
Run Code Online (Sandbox Code Playgroud)
但我想改变
<asp:TemplateField HeaderText="Description">
Run Code Online (Sandbox Code Playgroud)
至
<asp:TemplateField HeaderText='<%# GetById("atforbedringsforslag_description_title") %>'>
Run Code Online (Sandbox Code Playgroud)
但后来我明白了
仅在具有DataBinding事件的对象上支持数据绑定表达式.System.Web.UI.WebControls.TemplateField没有DataBinding事件.
我该如何设置此字段?我可以找到一些使用OnRowCreated,但随后你访问带有索引号的字段,然后很容易出错或忘记更改索引如果以后添加新字段
编辑我的解决方案:
创建自定义表达式构建器
using System.Web.Compilation;
using System;
using System.CodeDom;
public class LocalizationExpressionBuilder : ExpressionBuilder
{
public override CodeExpression GetCodeExpression(System.Web.UI.BoundPropertyEntry entry, object parsedData, ExpressionBuilderContext context)
{
CodeExpression[] inputParams = new CodeExpression[] { new CodePrimitiveExpression(entry.Expression.Trim()),
new CodeTypeOfExpression(entry.DeclaringType),
new CodePrimitiveExpression(entry.PropertyInfo.Name) };
// Return a CodeMethodInvokeExpression that will invoke the GetRequestedValue method using the specified input parameters
return new CodeMethodInvokeExpression(new CodeTypeReferenceExpression(this.GetType()),
"GetRequestedValue",
inputParams);
}
public static object GetRequestedValue(string key, Type targetType, string propertyName)
{
// If we reach here, no type mismatch - return the value
return GetByText(key);
}
//Place holder until database is build
public static string GetByText(string text)
{
return text;
}
}
Run Code Online (Sandbox Code Playgroud)
在我的web.config中添加了前缀
<system.web>
<compilation debug="true" defaultLanguage="c#" targetFramework="4.0">
<expressionBuilders>
<add expressionPrefix="localizeByText" type ="LocalizationExpressionBuilder"/>
</expressionBuilders>
</compilation>
</system.web>
Run Code Online (Sandbox Code Playgroud)
我现在可以得到这样的文字了
<asp:TemplateField HeaderText='<%$ localizeByText:Some text %>'>
Run Code Online (Sandbox Code Playgroud)
您可以构建自己的自定义Expression Builder调用GetById方法.请查看以下链接以获取解释如何构建表达式构建器以及如何使用它的旧文章:
http://www.4guysfromrolla.com/articles/022509-1.aspx
如果有表达式构建器,则将其与<%$语法一起使用.这与数据绑定语法不同<%#.
对于HeaderText字段,不允许使用DataBinding语法(不确定原因,但MS就是这样做的).使用表达式语法IS,一旦完成自定义表达式构建器,它就会起作用.
请浏览我链接的页面,它是相当多的文本,但最终使你的表达式构建器不会花费太多精力......
此外,该页面底部还有一个链接到作者所创建的表达式构建器库.看看它们,也许其中一个可以直接用来解决你的问题(特别是,CodeExpressionBuilder).
| 归档时间: |
|
| 查看次数: |
5275 次 |
| 最近记录: |