set selectedItem of list in viewmodel - cleaner way? [closed]

asked 2013-02-20 21:50:19 +0800

rickcr gravatar image rickcr
704 7

I'm finding setting a selectedItem of a listbox a bit ugly and verbose when using an MVVM approach. Is there any cleaner way to do things than as illustrated below...

Let's say you have a single select list box:

<listbox rows="1" model="@load(vm.animals)" selectedItem="@bind(vm.selectedAnimal)">

In order to have the proper selectedItem selected when viewing the page, you seem to always need to pass it the exact reference from your collection (selectedAnimal has to be the exact reference to the one from the animals collection.)

Let's say I"m populating the page for an edit. In order to have the animal selected I have to iterate over the list of animals in my view model and compare my selectedAnimal with the one in the list, looking a the value, and if it matches I reset the selectedAnimal to the one from the collection. That seems like a lot of work.

For example...

public void setUpForEdit() {  

if (selectedAnimal != null) {
 for(Animal animal: getAnimals()) {
    if (animal.getValue().equals(selectedAnimal.getValue())) {

How to others handle this sort of thing in a cleaner way?

delete flag offensive retag edit

The question has been closed for the following reason "the question is answered, right answer was accepted" by rickcr
close date 2013-02-25 23:19:29


selectedAnimal means object of Animal class why you comparing it with List item?

sjoshi ( 2013-02-21 08:59:42 +0800 )edit

have you implemented equals() in Animal?

dennis ( 2013-02-25 01:26:59 +0800 )edit

Sorry for the late reply. (some reason not getting email notifications?) That was it Dennis! I thought I had checked that, but apparently I had my equals wrong. Thanks!

rickcr ( 2013-02-25 23:18:54 +0800 )edit

Question tools




Asked: 2013-02-20 21:50:19 +0800

Seen: 33 times

Last updated: Feb 20 '13

Support Options
  • Email Support
  • Training
  • Consulting
  • Outsourcing
Learn More