[英]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
是一個Person
而Item.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.