我们有几个 ASP.Net 数据 View 列模板,它们根据用户选择的列动态添加到数据 View 中。
这些模板化单元需要处理自定义数据绑定(bind):
public class CustomColumnTemplate:
ITemplate
{
public void InstantiateIn( Control container )
{
//create a new label
Label contentLabel = new Label();
//add a custom data binding
contentLabel.DataBinding +=
( sender, e ) =>
{
//do custom stuff at databind time
contentLabel.Text = //bound content
};
//add the label to the cell
container.Controls.Add( contentLabel );
}
}
...
myGridView.Columns.Add( new TemplateField
{
ItemTemplate = new CustomColumnTemplate(),
HeaderText = "Custom column"
} );
首先,这看起来相当困惑,但也存在资源问题。
Label
已生成,无法在 InstantiateIn
中处理因为那样它就不会在那里进行数据绑定(bind)。这些控件有更好的模式吗?
有没有办法确保在数据绑定(bind)和渲染之后处理标签?
最佳答案
我已经广泛使用模板控制,但我还没有找到更好的解决方案。
为什么要在事件处理程序中引用 contentLable?
发件人是标签,您可以将其转换为标签并具有对标签的引用。如下所示。
//add a custom data binding
contentLabel.DataBinding +=
(object sender, EventArgs e ) =>
{
//do custom stuff at databind time
((Label)sender).Text = //bound content
};
然后您应该能够在 InstantiateIn 中处理标签引用。
请注意,我没有对此进行测试。
关于.net - 动态添加的 Web.UI.ITemplate 类的最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29976/