ASP.NET:用户控制访问到它包装的控件 [英] ASP.NET: User control with access to the controls that it wraps

查看:149
本文介绍了ASP.NET:用户控制访问到它包装的控件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一堆这样的样板code的出现在我的ASP.NET项目。

I have a bunch of occurrences of this kind of boilerplate code in my ASP.NET project.

<div class="inputfield">
  <div class="tl">
    <span class="tr"><!-- --></span>
    <span class="ll"><!-- --></span>
    <div class="lr">
      <div class="cntnt">
        <asp:TextBox .../>
      </div>
    </div>
  </div>
</div>

正如你可能已经猜到了,一切都在这片段是除了最里面的文本字段纯样板。

As you may have guessed, everything in that snippet is pure boilerplate except for the innermost text field.

什么是避免这种ASP.NET样板的最好方法?在如Django的我会做一个自定义标签吧,因为这样:

What is the best way to avoid such boilerplate in ASP.NET? In e.g. Django I would make a custom tag for it, as such:

{% boiler %}
<input ... />
{% endboiler %}

我在想,也许我可以创建一个用户的控制,但我已经找到了ASP.NET的用户控件的所有教程是非常简单和自闭,即他们不知道的内容标签。我需要沿着线的东西:

I was thinking that maybe I can create a user control, but all the tutorials on ASP.NET user controls that I've found are very simplistic and "self-closing", i.e. they are not aware of the contents of the tag. I need something along the lines of:

<Hello:MyControl>
  <asp:TextBox .../>
</Hello>

所以我的问题是:什么是避免了样板的最好办法

So my question is the following: what's the best way to avoid the boilerplate?

推荐答案

您可以使用的ITemplate属性。因此,你可以注入在不同情况下不同的内容。

You can use an ITemplate property. Thus, you can inject different content in different situations.

[PersistChildren(false), ParseChildren(true, "ContentTemplate")]
public partial class WebUserControl1 : System.Web.UI.UserControl
{

    [System.ComponentModel.Browsable(false), System.Web.UI.PersistenceMode(PersistenceMode.InnerProperty)]
    public ITemplate ContentTemplate { get; set; }

    protected override void CreateChildControls()
    {
        if (this.ContentTemplate != null)
            this.ContentTemplate.InstantiateIn(this);

        base.CreateChildControls();
    }
}

这篇关于ASP.NET:用户控制访问到它包装的控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆