2013-03-25 58 views
0

我想从页面向Web用户控件传递值列表。如何在Web用户控件中创建键值对属性

事情是这样的:

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

如何创建某种在Web用户控制键 - 值对属性(字典,哈希表)的。

回答

0

我已经找到了一种解决方案:

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; } 
    } 
} 

在页面上:

<%@ 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> 
0

您可以创建背后的用户控件的代码中的一个公共Dictionary属性:

public Dictionary<int, string> 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; 
+0

就我而言,我不能落后,所以我必须在我的例子做到这一点从正面像访问或更改代码。谢谢。 – drazen 2013-03-26 09:22:12

+0

啊。在这种情况下,您可以简单地使用控件下方的服务器标记来设置值: ' <%Dictionary newDictionary = new词典(); newDictionary.Add(1,“one”); ... MyUserControl.NameValuePair = newDictionary; %>确保在Dictionary集合的页面顶部添加<%@ Import Namespace =“System.Collections.Specialized”%>'。在您的控件上创建公共属性也可以做到这一点。只需使用服务器标签。 – McCee 2013-03-26 14:32:06

+0

谢谢。这会起作用,但不是在我的情况。我需要在用户控件加载事件中的字典值,在你的例子中,我没有在渲染事件中有值的情况(这对我来说是晚了)。 我已经发布了我的解决方案,我最好能在这一刻。它正在工作:) – drazen 2013-03-26 14:50:06