动态添加Web.UI.ITemplate类的最佳实践

时间:2020-03-05 18:43:47  来源:igfitidea点击:

我们有几个ASP.Net数据视图列模板,这些模板根据用户选择的列动态添加到数据视图中。

这些模板化的单元需要处理自定义数据绑定:

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"
    } );

首先,这看起来很混乱,但是也存在资源问题。 "标签"已生成,因此无法将其放置在" InstantiateIn"中,因为这样就无法在那里进行数据绑定。

这些控件是否有更好的模式?

有没有办法确保在数据绑定和渲染之后放置标签?

解决方案

回答

我已经广泛地使用模板控件,但没有找到更好的解决方案。

为什么在事件处理程序中引用contentLable?

发件人是标签,我们可以将其转换为标签,并具有对标签的引用。像下面一样。

//add a custom data binding
        contentLabel.DataBinding +=
            (object sender, EventArgs e ) =>
            {
                //do custom stuff at databind time
                ((Label)sender).Text = //bound content
            };

然后,我们应该可以在InstantiateIn中处理标签引用。

请注意,我尚未对此进行测试。