views:

82

answers:

2

I have a combobox bound to a collection, so the user can select one of the items. So far, so good.

The content of the combo box is driven by the item, but also by a value in my viewmodel. Imagine the value in my viewmodel is the language, I have dictionary of descriptions by language in my bound item, and I want to display the correct one.

How should I go about this?

+2  A: 

This is a classic example of why the ViewModel exists - you want to have logic which depends on trivial state in the view, as well as the main model.

Imagine you are writing a unit test to run against the ViewModel for this behaviour. You would need the ViewModel to have a property mapped to the selected item. The ViewModel would also have another property which varies according to this selected item as well as the other value in the ViewModel you mentioned.

I think of this as the test-driven approach to ViewModel design - if you can't write a unit test to evaluate it then you haven't got the mix of state and published interfaces right.

So, yes, the ViewModel can solve the problem and if you push all the state down into it you can do the unification within the ViewModel.

Andy Dent
Andy, this is the solution I'd be most comfortable with, but I can't figure out how best to do it. Would I have to implement a custom type for the combobox to bind to, and when I'm notified of a change, I should push the value back to the model?
James L
Do you want the entire set of descriptions for the combo to change according this other value?
Andy Dent
Sorry Andy, I missed your comment. Yes, I need the entire set of descriptions to change. I can think of a few ways to do it, none of them particularly good :)
James L
+1  A: 

Make an observable collection in your viewmodel of type Item. Bind the itemsource of your viewmodel to this observable collection.

public class Item
{
public String description {get;set;}
public String language {get;set;}
public override ToString()
{
      return description;
}
}

Selected item would also be bound to a property of type Item as well.

The override of ToString displays the description.

The Selected item propery will have a reference to the selected object property where you can get the language from.

zachary