Bind to specific item in collection without indexer

会有一股神秘感。 提交于 2020-01-06 15:17:21

问题


I am using an EF5 datamodel, in which the related entities are collected into a HashSet. I want to bind an element to the first related entity in the HashSet. I've seen answers on SO (here and here) which suggest using the following:

<DataGridComboBoxColumn SelectedValueBinding="{Binding LeadSteps[0].NewZoneID}"/>

but this relies on the collection having an indexer, which HashSet doesn't have.

(If this cannot be done, I can create a property in a partial class to the entity, and bind to that.)

How can I bind to the n-th item in a collection when the collection doesn't implement an integral indexer?


回答1:


I know it's an old question, but i also ran into just the same problem and found a solution i thought to share.

What worked for me was changing the declaration of the referencing member from:

public virtual ICollection<MyType> MyVarName { get; set; }

to:

public virtual IList<MyType> MyVarName { get; set; }

After this change, the collection items were accessible with the normal accessor:

<TextBlock Text="{Binding MyVarName[0].MyMemberName}" />



回答2:


You might need to rethink this whole situation. A HashSet is a 'set' of unique items, not a collection. A set is simply meant to maintain a group of members and to enable you to check whether a particular item is a member or not... there's no indexing because there is no order amongst the set items.

Although you can call the Enumerable.ElementAt<TSource> method on a HashSet, you cannot guarantee that it will return the same element when providing the same input value to the method. Most importantly, if the order of items in the HashSet is important to you, then you should be using a collection instead.

However, if you choose to ignore this advise, this is how you could achieve your requirement... just define a wrapper property for your single HashSet value... you could try something like this:

public YourHashSetDataType Hash
{
    get { return LeadSteps.ElementAt(0).NewZoneID; }
    set { LeadSteps.ElementAt(0).NewZoneID = value; NotifyPropertyChanged("Hash"); }
}


来源:https://stackoverflow.com/questions/21552403/bind-to-specific-item-in-collection-without-indexer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!