Moo33
Moo33

Reputation: 1283

How to bind values from a list of dictionaries to a ListView?

I have a List. Each item in the list has a dictionary item with 2 keys/values.

public List<Dictionary<string, object>> listOfDictionaries;
public Dictionary<string, object> aDict;

public void AddToList()
{
  aDict = new Dictionary<string, object> ();
  aDict[KEY_1] = "Value 1";
  aDict[KEY_2] = "Value 2";
  listOfDictionaries.add(aDict);

  aDict = new Dictionary<string, object> ();
  aDict[KEY_1] = "Value 3";
  aDict[KEY_2] = "Value 4";
  listOfDictionaries.add(aDict);

  MyListView.ItemSource = listOfDictionaries;
}

Now I would like to bind my dictionary items to my ListView in XAML.

<ListView Name:"MyListView" />

However doing this only shows the word 'Collection' in MyListView. I would like MyListView to display all my values from all my dictionaries. For example:

First row:
Value 1 + Value 2

Second row:
Value 3 + Value 4

And so forth. Btw, KEY_1 & KEY_2 are both constants with their values determined in a different file.

I've went through many examples online but they either seem too confusing or they're just binding to one dictionary. Any help is greatly appreciated. Thanks!

Upvotes: 0

Views: 1419

Answers (2)

Domysee
Domysee

Reputation: 12846

To use objects that can have dynamic property names, ExpandoObject and dynamic is the way to go.

List<dynamic> list = new List<dynamic>();

public void AddToList()
{
    dynamic d1 = new ExpandoObject();
    ((IDictionary<string, object>)d1)[KEY_1] = "Value 1";
    ((IDictionary<string, object>)d1)[KEY_2] = "Value 2";
    list.Add(d1);

    dynamic d2 = new ExpandoObject();
    ((IDictionary<string, object>)d2)[KEY_1] = "Value 3";
    ((IDictionary<string, object>)d2)[KEY_2] = "Value 4";
    list.Add(d2);

    MyListView.ItemSource = listOfDictionaries;
}

Upvotes: 1

Chirag Shah
Chirag Shah

Reputation: 981

Yeah, create a class named item have properties valueA and value B and valeAplusValueB which is the sum. Populate the list of items and set the source of litview with your listview item binded to the valueAplusValueB property

Upvotes: 0

Related Questions