Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/286.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# Web控件属性_C#_Asp.net - Fatal编程技术网

C# Web控件属性

C# Web控件属性,c#,asp.net,C#,Asp.net,我希望使我的web控件在设计模式下更具可读性,基本上我希望标记声明如下所示: <cc1:Ctrl ID="Value1" runat="server"> <Values>string value 1</Value> <Values>string value 2</Value> </cc1:Ctrl> 字符串值1 字符串值2 假设代码中有一个私有变量: List<string&g

我希望使我的web控件在设计模式下更具可读性,基本上我希望标记声明如下所示:

<cc1:Ctrl ID="Value1" runat="server">        
     <Values>string value 1</Value>
     <Values>string value 2</Value>
</cc1:Ctrl>

字符串值1
字符串值2
假设代码中有一个私有变量:

List<string> values = new List<string>();
列表值=新列表();
那么,如何让我的用户控件用标记中声明的值填充私有变量呢


对不起,我应该说得更清楚些。基本上我喜欢ITemplate提供的功能()

但在这种情况下,您需要知道在运行时可以实例化多少个模板,即

void Page_Init() {
if (messageTemplate != null) {
    for (int i=0; i<5; i++) {
        MessageContainer container = new MessageContainer(i);
        messageTemplate.InstantiateIn(container);
        msgholder.Controls.Add(container);
    }
}
void Page_Init(){
if(messageTemplate!=null){

对于(int i=0;i我看到了两个选项,但这两个选项都取决于您的web控件为您的值实现某种类型的集合。第一个选项是只使用控件的集合而不是您的私有变量。另一个选项是在运行时将控件的集合复制到您的私有变量(例如,可能在页面加载事件处理程序中)

假设您有一个实现项集合的web控件,如listbox。标记在源代码视图中如下所示:

    <asp:ListBox ID="ListBox1" runat="server">
        <asp:ListItem>String 1</asp:ListItem>
        <asp:ListItem>String 2</asp:ListItem>
        <asp:ListItem>String 3</asp:ListItem>
    </asp:ListBox><br />

字符串1
字符串2
字符串3

然后可以使用如下代码加载私有变量:

        List<String> values = new List<String>();

        foreach (ListItem item in ListBox1.Items)
        {
            values.Add(item.Value.ToString());
        }
列表值=新列表();
foreach(ListBox1.Items中的ListItem项)
{
Add(item.Value.ToString());
}
如果在Page_Load中执行此操作,您可能只希望在初始加载时执行(即,不在回发时执行)。另一方面,根据使用方式,您可以使用ListBox1.Items集合,而不是声明和初始化values变量


我想不出以声明方式执行此操作的方法(因为您的列表在运行时之前不会被实例化)。

我认为您要搜索的是属性:

[PersistenceMode(PersistenceMode.InnerProperty)]

请记住,您必须将名称空间和前缀注册到:

<%@ Register Namespace="MyNamespace" TagPrefix="Pref" %>

<%@ Register Namespace="MyNamespace" TagPrefix="Pref" %>