代码之家  ›  专栏  ›  技术社区  ›  Ed James

C#自定义控件,以获取内部文本作为字符串

  •  4
  • Ed James  · 技术社区  · 16 年前

    好的,我正在开发一个可以包含一些javascript的自定义控件,并将其从页面读取到一个字符串字段中。

    这是updatepanel中动态javascript的解决方案。

    目前,我已经让它工作了,但如果我试图在块内放置一个服务器标记:

    <custom:control ID="Custom" runat="server">
        <%= ControlName.ClientID %>
    </custom:control>
    

    编译器不喜欢它。我知道这些都是在运行时生成的,所以可能与我正在做的不兼容,但有人知道我如何才能让它们工作吗?

    编辑

    错误消息是:在此上下文中不支持代码块

    编辑2

    控件:

    [DataBindingHandler("System.Web.UI.Design.TextDataBindingHandler, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"), ControlValueProperty("Text"), DefaultProperty("Text"), ParseChildren(true, "Text"), AspNetHostingPermission(SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal), AspNetHostingPermission(SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal)]
    public class CustomControl : Control, ITextControl
    {
        [DefaultValue(""), Bindable(true), Localizable(true)]
        public string Text
        {
            get
            {
                return (string)(ViewState["Text"] ?? string.Empty);
            }
    
            set
            {
                ViewState["Text"] = value;
            }
        }
    }
    
    1 回复  |  直到 16 年前
        1
  •  1
  •   War    16 年前

    编译器是写的,服务器端代码块仅在ITemplate的上下文中受支持。

    “文本”属性应该这样设置。。。

    <custom:control ID="Custom" runat="server" Text="YourText">
    

    使用ITemplate,您可以在codebehind中将其声明为。。。

    public ITemplate Text
    {
        get;
        set;
    }
    

    但是你需要这样做。。。

    <custom:control ID="Custom" runat="server">
       <Text><%= ControlName.ClientID %></Text>
    </custom:control>
    

    话虽如此,如果你有一个自定义控件,为什么不在代码背后这样做呢。。。

    this.text = ((ITextControl)Page.FindControl(controlName)).Text;
    

    问题是,它不是很有活力。

    我倾向于模板化选项。 但实施起来更难。