Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I have a ValueConverter in my ViewModel?

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?

like image 291
James L Avatar asked Jul 18 '10 10:07

James L


People also ask

How do I connect ViewModel view?

This can be done directly in xaml (the View just instances the ViewModel directly). This can be done in the View's constructor ( this. DataContext = new MyViewModel(); )

What is a value converter?

A value converter is a class whose responsibility is to convert view-model values into values that are appropriate to display in the view and vice versa.

What is converter in xamarin forms?

The Convert method is called when data moves from the source to the target in OneWay or TwoWay bindings. The value parameter is the object or value from the data-binding source. The method must return a value of the type of the data-binding target.


2 Answers

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.

like image 59
Andy Dent Avatar answered Oct 25 '22 10:10

Andy Dent


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.

like image 41
zachary Avatar answered Oct 25 '22 12:10

zachary