2016-05-09 21 views
0

我有一個UserControl,它的工作原理與<asp:Panel>非常相似。用戶控件的內部屬性不支持代碼塊,但在面板中受支持嗎?

雖然面板可以做到這一點:

<uc1:NotPanel runat="server"> 
    <img src='<%= ResolveUrl("~/img.png")%>' /> 
</uc1:NotPanel> 

error: Code blocks are not supported in this context

NotPanel被引用,像這樣:

<%@ Register Src="~/Controls/NotPanel.ascx" TagName="NotPanel" TagPrefix="uc1" %> 

<asp:Panel runat="server"> 
    <img src='<%= ResolveUrl("~/img.png")%>' /> 
</asp:Panel> 

與我的控制嘗試這個,當我得到一個錯誤

並定義如下(這是一個gros狡猾的簡裝版):

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="NotPanel.ascx.cs" Inherits="MyNamespace.NotPanel" %> 
<div class="something"> 
    <asp:PlaceHolder ID="phControls" runat="server" /> 
</div> 

這個代碼隱藏:

[ParseChildren(true, "Content")] 
[PersistChildren(false)] 
public partial class NotPanel : System.Web.UI.UserControl 
{ 
    [PersistenceMode(PersistenceMode.InnerDefaultProperty)] 
    public Control Content { get; set; } 

    public void Page_Init(object sender, EventArgs e) 
    { 
     phControls.Controls.Add(Content); 
    } 
} 

難道我做錯了這個類的定義,我不能使用代碼塊?或者這是UserControls的限制嗎?

:一個 <asp:CompareValidator>內的相同的控制不能引用它,沒有得到以下錯誤 -

一個相關的問題(據推測具有相同的原因),當文本框被置於內這些控制中的一個發生

Unable to find control id 'txtCompareTo' referenced by the 'ControlToCompare' property of 'compareValidator'.

同樣,當<uc1:NotPanel>替換爲<asp:Panel>時,此工作正常。有什麼可以做到這一點?

回答

0

據我所知(我很樂意予以糾正),你不能像這樣將代碼塊注入用戶控件。

用戶控件基本上是迷你獨立頁面,通常與其父母分離。而且它們並不像名稱可能暗示的那樣是實際的自定義網頁控件。

但是,您可以通過屬性傳遞值。因此,在您的用戶控制ascx.cs包含這樣的內容:

private string _myImagePath; 
public string MyImagePath 
{ 
    get 
    { 
     return _myImagePath; 
    } 
    set 
    { 
     _myImagePath = value; 
    } 
} 

protected void Page_Load(object sender, EventArgs e) 
{ 
    //do stuff 
} 

然後,你可以做<uc1:NotPanel runat="server" MyImagePath="Foo" />

OR

在ASPX:<uc1:NotPanel runat="server" ID="MyUserControl" /> 並在代碼隱藏:MyUserControl.MyImagePath = "Foo";

+0

謝謝,但雖然這可以解決這個特定情況,但此控件的用例是作爲各種新舊標記塊的「包裝器」,所以我不想添加特定內容的處理到控制本身。 – FTWinston

+1

@FTWinston然後,您需要查看自定義控件(ASP.NET服務器控件)而不是用戶控件。看看http://www.codeproject.com/Articles/28783/Your-First-ASP-NET-Custom-Control –

+0

有一個去使用CustomControl,並得到相同的錯誤:代碼塊不支持在這上下文。 – FTWinston

0

這這聽起來很奇怪,但如果你圍繞包含代碼塊的標記代碼進行控制,運行時錯誤可能會消失。

雖然智能感知可能會有點抱怨。

相關問題