[英]How to set element visibility from codebehind
我正在嘗試基於EPiServer中設置的頁面屬性,從codebehind文件的aspx頁面設置控件的可見性。 相關控件的編碼如下:
<asp:Content ContentPlaceHolderID="RelatedContent" runat="server">
<p id="DateProp" runat="server" Visible ="<%# DateVisible %>"><strong>Date:</strong> <%= ((DateTime)CurrentPage["EventDate"]).ToString("d MMMM yyyy") %></p>
</asp:Content>
基於這個先前的問題 ,我嘗試了幾種不同的方法來實現它,但是我一直無法使其工作。 首先,我嘗試了這個:
public partial class Event : EPiServer.TemplatePage<EventPage>
{
public bool DateVisible = (bool)CurrentPage["HideDate"] == true ? false : true;
protected void Page_Load(object sender, EventArgs e)
{
DataBind();
}
}
出現錯誤“ Error 80 An object reference is required for the non-static field, method, or property EPiServer.PageBase<JamesTrustWF.Web.Models.Pages.EventPage>.CurrentPage.get'
”
然后我嘗試了這個:
public partial class Event : EPiServer.TemplatePage<EventPage>
{
public bool DateVisible = true;
protected void Page_Load(object sender, EventArgs e)
{
DateVisible = (bool)CurrentPage["HideDate"] == true ? false : true;
DataBind();
}
}
出現錯誤“ Object reference not set to an instance of an object
”。 知道如何使其工作嗎?
您的第一個示例失敗的原因僅是因為在初始化實例字段時無法引用其他實例成員,因為這樣做只是在調用構造函數之前完成的,請參見http://msdn.microsoft.com/zh-cn/library /ms173118.aspx
在這種情況下,關鍵的事情是如果將EPiServer中的屬性視為空,則它們將返回null。 這意味着具有空字符串值的字符串屬性將返回null,而具有false值的布爾屬性也將返回null。
因此,在您的情況下,當您想為布爾屬性分配值時,只需檢查該屬性是否返回任何值。
DateVisible = CurrentPage["HideDate"] == null;
另一個選擇是使用PageBase類上的IsValue方法進行檢查。
DateVisible = !IsValue("HideDate");
另外,由於您使用的是強類型頁面類型,因此可以僅在當前頁面上使用該屬性(假設已通過這種方式添加了HideData屬性)
DateVisible = !CurrentPage.HideDate;
最后,您也可以直接從后面的代碼中分配visible屬性,而無需遍歷DateVisible字段和DataBind。
public partial class Event : EPiServer.TemplatePage<EventPage>
{
protected void Page_Load(object sender, EventArgs e)
{
DateProp.Visible = !CurrentPage.HideDate;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.