代码之家  ›  专栏  ›  技术社区  ›  Keith

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

  •  4
  • Keith  · 技术社区  · 17 年前

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

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

    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 因为那样就不会有数据绑定了。

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

    是否有方法确保标签在数据绑定和呈现后被丢弃?

    2 回复  |  直到 17 年前
        1
  •  2
  •   David Basarab    17 年前

    我广泛使用了模板控制,但还没有找到更好的解决方案。

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

    发件人是标签,您可以将其投射到标签上并引用标签。如下图所示。

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

    然后,您应该能够在InstantiateIn中处理标签引用。

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

        2
  •  1
  •   jackvsworld    12 年前

    一种解决方案是制作模板 它本身 实施 IDisposable ,然后处置模板中的控件 Dispose 方法。当然,这意味着您需要某种集合来跟踪您创建的控件。以下是一种方法:

    public class CustomColumnTemplate :
        ITemplate, IDisposable
    {
        private readonly ICollection<Control> labels = new List<Control>();
    
        public void Dispose()
        {
            foreach (Control label in this.labels)
                label.Dispose();
        }
    
        public void InstantiateIn(Control container)
        {
            //create a new label
            Label contentLabel = new Label();
    
            this.labels.Add(contentLabel);
    

    ...

            //add the label to the cell
            container.Controls.Add( contentLabel );
        }
    }
    

    现在,您仍然面临着处理模板的问题。但至少你的模板将是一个负责任的内存消费者,因为当你调用时 处置 在模板上,其所有标签都将随模板一起处理。

    更新

    This link on MSDN 建议您的模板可能不需要实现 可识别 因为控件将植根于页面的控件树中,并由框架自动处理!

    推荐文章