Question

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?

Was it helpful?

Solution

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}" />

OTHER TIPS

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"); }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top