繁体   English   中英

将字典绑定到转发器

[英]Bind dictionary to repeater

我有一个字典对象<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()

在绑定字典中的条目类型的代码隐藏中编写属性。 所以说,例如,我将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是一个PersonItem.Value是一个int ,它们是强类型的。

当然,您可以(读取: 应该 )将Item重命名为更符合字典条目的内容。 仅这一点将有助于减少我的示例用法中命名的任何歧义。

肯定没有什么可以阻止你定义一个额外的属性,比如说:

protected Person CurrentPerson
{
    get { return ((KeyValuePair<Person, int>)this.GetDataItem()).Key; }
}

并在你的标记中使用它:

<span><%# this.CurrentPerson.FirstName %></span>

...这些都无法阻止您访问相应的词典条目的.Value

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM