简体   繁体   English

从代码背后访问asp.net自定义控件的访问属性

[英]access property of asp.net custom control from code behinde

I create a asp.net custom control 我创建一个asp.net自定义控件

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="control.ascx.cs" Inherits="test.control.control" %>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>

I have drop it in an aspx page and I want to use Text property of the custom control but the custom control does not have Text property. 我将其放在aspx页面中,我想使用自定义控件的Text属性,但是自定义控件没有Text属性。

<uc1:control runat="server" id="control" />

You need to add a property to your code behind that represents the text property of the textbox. 您需要在代码后面添加一个属性,该属性表示文本框的text属性。

So within control.ascx.cs 因此在control.ascx.cs中

public string Text
{
    get { return TextBox1.Text; }
    set { TextBox1.Text = value; }
}

Then this will work 这样就可以了

<uc1:control runat="server" id="control" Text="My Control" />

Just to clarify - custom controls don't naturally inherit the properties of the child controls, for example, what would you expect to happen if the control had 2 textbox controls? 需要澄清的是-自定义控件不会自然地继承子控件的属性,例如,如果控件具有2个文本框控件,您会期望发生什么? So for each property that you want your custom control to expose you need to add a property to the code behind. 因此,对于您希望自定义控件公开的每个属性,都需要向后面的代码中添加一个属性。 You can even add properties that don't relate to the properties of the child controls and keep the value in a hidden field or control state or even viewstate. 您甚至可以添加与子控件的属性不相关的属性,并将该值保留在隐藏字段或控件状态甚至视图状态中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM