在代码前面设置的用户控件属性在OnPreRender中为null [英] User control property set in code front is null in OnPreRender
问题描述
TestPage
有一个属性 Items
,我想传递到我的自定义用户控件 Control
中.我喜欢在代码前设置属性的语法,因此TestPage.aspx看起来像这样……
TestPage
has a property Items
I want to pass into my custom user control Control
. I like the syntax of setting the property in code-front, so TestPage.aspx looks like this...
页面:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="TestPage.aspx.cs" Inherits="TestPage" %>
<%@ Register Src="~/Control.ascx" TagPrefix="custom" TagName="Control" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head><title>Test Page</title></head>
<body>
<custom:Control ID="TestControl" Items='<%# Items %>' runat="server" />
</body>
</html>
TestPage 的
后置代码具有 Items
属性和一个简单的getter:
Code-behind for TestPage
has the property Items
with a simple getter:
using System;
using System.Collections.Generic;
using System.Web.UI;
public partial class TestPage : Page
{
protected List<string> Items = new List<string>() { "Hello", "world!", };
}
控件:
我的自定义用户控件具有一个中继器,以呈现 Items
中的值.
My custom user control has a repeater to render the values in Items
.
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="Control.ascx.cs" Inherits="Control" %>
<asp:Repeater ID="Repeater" ItemType="System.string" runat="server">
<ItemTemplate>
<p><%# Item %></p>
</ItemTemplate>
</asp:Repeater>
该控件的隐藏代码公开了公共 Items
属性,并将其绑定到 Repeater
.
The control's code-behind exposes the public Items
property and binds it to the Repeater
.
using System;
using System.Collections.Generic;
using System.Web.UI;
public partial class Control : UserControl
{
public List<string> Items { get; set; }
protected override void OnPreRender(EventArgs e)
{
Repeater.DataSource = Items;
Repeater.DataBind();
}
}
问题:
呈现的页面为空,因为 OnPreRender
中的 Control.Items == null
.
The rendered page is empty, because Control.Items == null
in OnPreRender
.
如果我在 TestPage.Page_Load
中设置 TestControl.Items = Items
,则会在 Control.OnPreRender <中填充
Control.Items
/code>.
If I set TestControl.Items = Items
in TestPage.Page_Load
, Control.Items
is populated in Control.OnPreRender
.
那行得通,但是我很书呆子.在 TestPage
的代码前端中设置 Items
时,是否可以绑定转发器?
That works, but I'm pedantic. Is it possible to bind the repeater when Items
is set in TestPage
's code front?
推荐答案
<custom:Control ID="TestControl" Items='<%# Items %>' runat="server" />
仅在您调用控件的DataBind方法时执行:
will only be performed if you call the DataBind method of the control:
TestControl.DataBind();
如果页面具有其他数据绑定表达式,则可以选择调用 Page.DataBind()
,它将递归绑定所有子控件.
If your page has other data-binding expressions, you can alternatively call Page.DataBind()
, which will recursively bind all child controls.
这篇关于在代码前面设置的用户控件属性在OnPreRender中为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!