Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/33.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_Properties_Webforms_Web User Controls - Fatal编程技术网

C# 如何在web用户控件中创建键值对属性

C# 如何在web用户控件中创建键值对属性,c#,asp.net,properties,webforms,web-user-controls,C#,Asp.net,Properties,Webforms,Web User Controls,我想将值列表从页面传递给web用户控件 大概是这样的: <uc:MyUserControl runat="server" id="MyUserControl"> <DicProperty> <key="1" value="one"> <key="2" value="two"> ... </DicProperty> </uc:MyUserControl

我想将值列表从页面传递给web用户控件

大概是这样的:

<uc:MyUserControl runat="server" id="MyUserControl">
    <DicProperty>
        <key="1" value="one">
        <key="2" value="two">
               ...
    </DicProperty>  
</uc:MyUserControl>

...

如何在web用户控件中创建某种类型的键值对属性(dictionary,hashtable)。

您可以在用户控件后面的代码中创建公共
dictionary
属性:

公共字典NameValuePair{get;set;}

然后,在创建新用户控件的表单的代码隐藏中,可以填充该新属性:

Dictionary<int, string> newDictionary = new Dictionary<int, string>();

newDictionary.Add(1, "one");
newDictionary.Add(2, "two");
newDictionary.Add(3, "three");

MyUserControl.NameValuePair = newDictionary;
Dictionary newDictionary=newDictionary();
新字典。添加(1,“一”);
新增(2,“两”);
新增(3,“三”);
MyUserControl.NameValuePair=newDictionary;

我找到了一种解决方案:

public partial class MyUserControl : System.Web.UI.UserControl
{
    private Dictionary<string, string> labels = new Dictionary<string, string>();

    public LabelParam Param
    {
        private get { return null; }
        set
        { 
            labels.Add(value.Key, value.Value); 
        }
    }

    public class LabelParam : WebControl
    {
        public string Key { get; set; }
        public string Value { get; set; }

        public LabelParam() { }
        public LabelParam(string key, string value) { Key = key; Value = value; }
    }
}
公共部分类MyUserControl:System.Web.UI.UserControl
{
专用字典标签=新字典();
公共标签参数
{
私有get{return null;}
设置
{ 
标签.Add(value.Key,value.value);
}
}
公共类LabelParam:网络控制
{
公共字符串密钥{get;set;}
公共字符串值{get;set;}
公共LabelParam(){}
公共LabelParam(字符串键,字符串值){key=key;value=value;}
}
}
在网页上:

<%@ Register src="MyUserControl.ascx" tagname="MyUserControl" tagprefix="test" %>

<test:MyUserControl ID="MyUserControl1" runat="server">
    <Param Key="d1" value="ddd1" />
    <Param Key="d2" value="ddd2" />
    <Param Key="d3" value="ddd3" />
</test:MyUserControl>


在我的情况下,我无法访问或更改后面的代码,因此我必须像我的示例中那样从前面进行操作。谢谢。在这种情况下,您只需使用控件正下方的服务器标记来设置值:
确保在页面顶部为字典集合添加
。在控件上创建公共属性也可以执行同样的操作。只需使用服务器标签。谢谢。这会起作用,但对我来说不行。我需要在用户控件加载事件中使用字典的值,但在您的示例中,我在渲染事件中使用了值(对我来说太晚了)。我已经发布了我的解决方案,这是我目前所能做的最好的。它正在工作:)太棒了。我很高兴你明白了。