【发布时间】:2011-01-17 12:11:10
【问题描述】:
我有一个字典对象<string, string> 并想将它绑定到转发器。但是,我不确定在 aspx 标记中添加什么来实际显示键值对。没有抛出任何错误,我可以让它与 List 一起工作。如何让字典显示在转发器中?
【问题讨论】:
标签: c# asp.net data-binding dictionary repeater
我有一个字典对象<string, string> 并想将它绑定到转发器。但是,我不确定在 aspx 标记中添加什么来实际显示键值对。没有抛出任何错误,我可以让它与 List 一起工作。如何让字典显示在转发器中?
【问题讨论】:
标签: c# asp.net data-binding dictionary repeater
绑定到字典的值集合。
myRepeater.DataSource = myDictionary.Values
myRepeater.DataBind()
【讨论】:
myDictionary。在标记中,我使用了<%# Container.DataItem.ToString() %>。这是可行的,但它将键和值都显示为一个“项目”。有没有办法单独获取key 和value,以便它们可以分别格式化?
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")%> 为我工作。
【讨论】:
在绑定字典中的条目类型的代码隐藏中编写一个属性。比如说,我将Dictionary<Person, int> 绑定到我的中继器。我会(在 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。
【讨论】: