【发布时间】:2018-05-04 14:58:13
【问题描述】:
TestPage 有一个属性Items 我想传递给我的自定义用户控件Control。我喜欢在代码前端设置属性的语法,所以 TestPage.aspx 看起来像这样...
主页:
<%@ 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:
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 中的值。
<%@ 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。
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。
如果我在TestPage.Page_Load 中设置TestControl.Items = Items,Control.Items 将填充在Control.OnPreRender 中。
这行得通,但我很迂腐。在TestPage的代码前面设置Items时是否可以绑定转发器?
【问题讨论】:
-
你在任何地方都调用 TestControl.DataBind() 吗?
<%# ... %>语法仅在您在控件上调用 DataBind 时设置属性。 -
@MichaelLiu 那是票。我习惯于仅在内置控件的上下文中考虑数据绑定。出于某种原因,没有发生在自定义控件中执行此操作。放弃一个答案,我会接受它。