Saturday, February 5, 2011

Associating a ListView with a collection of objects

How can you use a ListView to show the user a collection of objects, and to manage those objects?

  • For the purpose of argument, here's our design goal: We've got a "monster" object, and that "monster" will have several "powers." The user interacts with the powers via a ListView item.

    First, we create a Power object. Give the object the following method:

    public ListViewItem makeKey()
    {
        return new ListViewItem(name);
    }
    

    where name is the name of the power, and a string. This ListViewItem will serve as a key, allowing us to identify and retrieve this power later.

    Next, we need to add somewhere in the Monster object to keep track of all these powers.

    public Dictionary<ListViewItem,Power> powers;
    

    So now we need a way to add powers to the monster.

    public void addPower(Power newPower) {
        ListViewItem key = newPower.makeKey();
        monster.powers.add(key, newPower);
    }
    

    Ok, almost done! Now we've got a dictionary of ListViewItems which are tied to the monster's powers. Just grab the keys from that dictionary and stick them in a ListView:

    foreach (ListViewItem key in powers.Keys)
        powerList.Items.Add(key);
    

    Where powerList is the ListView we're adding the ListViewItems to.

    Alright, so we've got the ListViewItems in the ListView! Now, how do we interact with those? Make a button and then a function something like this:

    private void powerRemoveButton_Click(object sender, EventArgs e)
    {
        if (powerList.SelectedIndices.Count > 0)
        {
            int n = powerList.SelectedIndices[0];
            ListViewItem key = powerList.Items[n];
            monster.powers.Remove(key);
            powerList.Items.Remove(key);
        }
        else
        {
            MessageBox.Show("No power selected.");
        }
    }
    

    And that's that. I hope you've found this helpful. I'm not sure if this was an intentional aspect of their design, but ListViews and Dictionaries blend together so amazingly well when you use a ListViewItem as a key that it's a joy!

    Josh : Seriously... you posted that much of an answer to your own question almost simultaneously.
    Asmor : I thought it was a handy tip, and it was suggested that I post and answer my own question if I wanted to share a tip. I typed the answer beforehand and pasted it after I submitted the question.
    From Asmor

0 comments:

Post a Comment