且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

ASP.NET Web用户控件的访问内在价值

更新时间:2023-12-06 10:15:34

我假设你的自定义控件有文本 string类型称为一个属性。如果再声明这个属性有余辉模式InnerDefaultProperty你应该得到你所期待的。

例如

  ///<总结>
///默认文本属性(内文HTML /标记)
///< /总结>
[PersistenceMode(PersistenceMode.InnerDefaultProperty)
公共字符串PropertyTest
{
    得到
    {
        对象o = this.ViewState [文字];
        如果(O!= NULL)
        {
            回报(字符串)O;
        }
        返回的String.Empty;
    }
    组
    {
        this.ViewState [文字] =值;
    }
}

编辑:
为了避免文字内容不允许你必须加入 [ParseChildren(真的,PropertyTest)] 来您的,以帮助解析器定义(见MSDN).

当然,你需要一个可写的属性(即它需要一个二传手,我之前省略急促)。

Surprised that i havent been able to find this myself, but anyway. Let's say i use my web user control like this:

<myprefix:mytag userid="4" runat="server">Some fancy text</myprefix:mytag>

How would i be able to access the text inside the tags from its codebehind ("Some fancy text")? Was expecting it to be exposed through this.Text, this.Value or something similar.

EDIT: I even get the following warning on the page where i try to user it: Content is not allowed between the opening and closing tags for element 'mytag'.

EDIT2:

public partial class mytag: UserControl
{
    public int ItemID { get; set; }
    protected void Page_Load(object sender, EventArgs e)
    {           
    }
}

I assume your custom control has a property called Text of type string. If you then declare this property to have the persistence mode "InnerDefaultProperty" you should get what you are looking for.

E.g.

/// <summary>
/// Default Text property ("inner text" in HTML/Markup)
/// </summary>
[PersistenceMode(PersistenceMode.InnerDefaultProperty)]
public string PropertyTest
{
    get
    {
        object o = this.ViewState["Text"];
        if (o != null)
        {
            return (string)o;
        }
        return string.Empty;
    }
    set
    {
        this.ViewState["Text"] = value;
    }
}

Edit: To avoid the "Literal Content Not Allowed" you have to help the parser by adding [ParseChildren(true, "PropertyTest")] to your class definition (see MSDN).

And of course you need a writable property (i.e. it needs a setter which I omitted for shortness before).