我有一个字典对象 <string, string>
,想将它绑定到重复器。然而,我不确定在aspx
标记中应该放什么来实际显示键-值对。没有抛出错误,我可以使用一个List
,但是如何使字典在重复器中显示呢?
我有一个字典对象 <string, string>
,想将它绑定到重复器。然而,我不确定在aspx
标记中应该放什么来实际显示键-值对。没有抛出错误,我可以使用一个List
,但是如何使字典在重复器中显示呢?
IDictionary<TKey,TValue>
也是一个ICollection<KeyValuePair<TKey, TValue>>
。
你需要绑定到类似以下内容的东西(未经测试):
((KeyValuePair<string,string>)Container.DataItem).Key
((KeyValuePair<string,string>)Container.DataItem).Value
请注意,返回的项的顺序是未定义的。它们可能以插入顺序返回小字典,但这并不保证。如果您需要有保证的顺序,则 SortedDictionary<TKey, TValue>
按键排序。或者,如果您需要不同的排序顺序(例如按值排序),可以创建一个 List<KeyValuePair<string,string>>
存储键值对,然后对其进行排序,并绑定到已排序的列表。<%# DataBinder.Eval((System.Collections.Generic.KeyValuePair<string, string>)Container.DataItem,"Key") %>
<%# DataBinder.Eval((System.Collections.Generic.KeyValuePair<string, string>)Container.DataItem,"Value") %>
<%# Eval("key")%>
对我很有用。
将绑定到字典的值集合。
myRepeater.DataSource = myDictionary.Values
myRepeater.DataBind()
myDictionary
。在标记中,我使用了 <%# Container.DataItem.ToString() %>
。这个方法可以工作,但它将键和值一起显示为一个“项”。有没有办法单独获取 key
和 value
,以便可以分别进行格式化? - XSL在您的代码后台编写一个属性,该属性的类型与绑定字典中的条目类型相同。例如,假设我将Dictionary<Person, int>
绑定到我的Repeater上。我会在我的代码后台编写一个类似于以下C#代码的属性:
protected KeyValuePair<Person, int> Item
{
get { return (KeyValuePair<Person, int>)this.GetDataItem(); }
}
在我看来,我可以像这样使用代码段:
<span><%# this.Item.Key.FirstName %></span>
<span><%# this.Item.Key.LastName %></span>
<span><%# this.Item.Value %></span>
Item.Key
是一个 Person
,Item.Value
是一个 int
,并且它们被强类型化了。Item
重命名为在字典中更具象征意义的名称。这样就可以减少示例使用中的任何歧义。protected Person CurrentPerson
{
get { return ((KeyValuePair<Person, int>)this.GetDataItem()).Key; }
}
并将其这样使用:
<span><%# this.CurrentPerson.FirstName %></span>
这并不妨碍您访问相应的字典条目的.Value
。