我设计了一个用户控件。它包含一个公共(public)属性“CurrentValue”。 当我尝试使用 Eval 表达式初始化属性时,分配了一个空值。
//在下面的代码中,标签赋值OK,RatingNull 用户控件赋值为空
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("Difficulty") %>'
<uc1:RatingNull ID="RatingNull1" runat="server" CurrentValue='<%# Eval("Difficulty") %>' />
</ItemTemplate>
如果我直接分配一个值(即 CurrentValue="5"),用户控件工作正常。
public partial class RatingNull : System.Web.UI.UserControl
{
private string _CurrentValue;
public string CurrentValue
{
get { return _CurrentValue; }
set { _CurrentValue = value; }
}
(...)
}
最佳答案
以下代码适用于我。什么时候使用 _CurrentValue
字段?
用户控件
public partial class Test1 : System.Web.UI.UserControl
{
public string CurrentValue
{
get { return (string)ViewState["CurrentValue"] ?? string.Empty; }
set { ViewState["CurrentValue"] = value; }
}
protected override void Render(HtmlTextWriter writer)
{
base.Render(writer);
writer.Write(this.CurrentValue);
}
}
页面
protected void Page_Load(object sender, EventArgs e)
{
var ds = new[]
{
new { FirstName = "F1", LastName = "L1" },
new { FirstName = "F2", LastName = "L2" },
};
DataList1.DataSource = ds;
DataList1.DataBind();
}
HTML 标记
<asp:DataList ID="DataList1" runat="server">
<ItemTemplate>
<uc1:Test ID="Test1" runat="server" CurrentValue='<%# Eval("FirstName") %>' />
</ItemTemplate>
</asp:DataList>
关于c# - ASP.NET 用户控件 : can't initialize a user control property using Eval ("..."),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2317089/