我找到了演示模板化用户控件的代码示例。它们可以很好地显示数据,但是我无法让它们用于输入数据。我的模板中有一个TextBox,可以更改其中的值,但我无法在代码中获得更改的值。我尝试在按钮单击处理程序中获取用户控件的值,但我总是得到初始值。此外,当我单击按钮时,模板化的用户控件的值将被重置。数据输入是否适用于模板化用户控件?
我的代码类似于MSDN主题"如何:创建模板化的ASP.NET用户控件"。
Default.aspx ===============================
<%@ Page Language="C#" %>
<%@ Register TagPrefix="uc" tagname="TemplateTest" Src="TemplatedUC.ascx" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<script runat="server">
protected void Page_Load()
{
DataBind();
}
protected void ButtonShowContent_Click(object sender, EventArgs e)
{
ContentLabel.Text = string.Format("Index: {0} - Message: {1}<br>", TemplateTest1.Index, TemplateTest1.Message);
}
</script>
<head runat="server">
<title>Templated User Control Test</title>
</head>
<body>
<h1>Testing Templated User Control</h1>
<form id="Form2" runat="server">
<uc:TemplateTest ID="TemplateTest1" runat="server">
<MessageTemplate>
Index: <asp:Label runat="server" ID="Label1" Text='<%# Container.Index %>' /><br />
Message: <asp:TextBox runat="server" ID="Label2" Text='<%# Container.Message %>' /><br />
</MessageTemplate>
</uc:TemplateTest>
<asp:Button ID="ButtonShowContent" runat="server" Text="Show Content" onclick="ButtonShowContent_Click" />
<asp:Label ID="ContentLabel" runat="server" Text=" " Width="100%" />
</form>
</body>
</html>
TemplatedUC.ascx ============================
<%@ Control Language="C#" ClassName="TemplatedUC" %>
<%@ Import Namespace="System.ComponentModel" %>
<script runat="server">
private ITemplate messageTemplate = null;
private MessageContainer container = new MessageContainer(1, "Initial Text");
[ TemplateContainer(typeof(MessageContainer)) ]
[ PersistenceMode(PersistenceMode.InnerProperty) ]
public ITemplate MessageTemplate {
get
{
return messageTemplate;
}
set
{
messageTemplate = value;
}
}
public int Index
{
get { return container.Index; }
set { container.Index = value; }
}
public string Message
{
get { return container.Message; }
set { container.Message = value; }
}
void Page_Init() {
if (messageTemplate != null) {
messageTemplate.InstantiateIn(container);
PlaceHolder1.Controls.Add(container);
}
}
public class MessageContainer: Control, INamingContainer {
private int m_index;
private String m_message;
internal MessageContainer(int index, String message)
{
m_index = index;
m_message = message;
}
public int Index {
get { return m_index; }
set { m_index = value; }
}
public String Message
{
get { return m_message; }
set { m_message = value; }
}
}
</script>
<asp:Placeholder runat="server" ID="PlaceHolder1" />
如果您运行此项并更改&#39;消息&#39;的值,则单击该按钮时,将显示数据。谢谢。