When is it a bad practice to use Value Converter?

ReedReed ✭✭Member ✭✭

In my ViewModel, I have a ObservableCollection of Orders. Order model has statuses like started, finished, cancelled. I bind the collection to a ListView to display the orders and I want to color the row according to the status.

Would it be a good solution and not violate MVVM principles if I would write a value converter to do it? I would map the statuses to the colors and use that value converter when binding the color of a row.

I'm asking this question, because all examples of value converters are very primitive (changing the format of a DateTime and etc.) and my suggested value converter would contain several if statements or a switch.

Are there any other alternative ways to achieve my desired behavior?

Best Answer

Answers

  • ReedReed ✭✭ Member ✭✭
    edited January 10

    Thanks, that's one of the answers that I've looked for.

    I mentioned alternative ways to do this and would it be a good alternative to have ObservableCollection of OrderViewModel on my OrdersViewModel? I could extract the ListView's, which is bound to OrdersViewModel, data template to another view and set the view's BindingContext to OrderViewModel. This way I could expose status-to-color behavior through properties of OrderViewModel.

    One flaw that I see with value converter approach is that I might end up creating a lot of value converters if I need more transformations like this, whereas in my suggested approach, all the transformations would be on the ViewModel exposed as properties.

  • NMackayNMackay mod GBInsider, University mod

    @Reed said:
    Thanks, that's one of the answers that I've looked for.

    I mentioned alternative ways to do this and would it be a good alternative to have ObservableCollection of OrderViewModel on my OrdersViewModel? I could extract the ListView's, which is bound to OrdersViewModel, data template to another view and set the view's BindingContext to OrderViewModel. This way I could expose status-to-color behavior through properties of OrderViewModel.

    One flaw that I see with value converter approach is that I might end up creating a lot of value converters if I need more transformations like this, whereas in my suggested approach, all the transformations would be on the ViewModel exposed as properties.

    I wouldn't recommend that, the viewmodel is for business logic, not presentation logic. That's just my take and I've argued with Xamarin Uni lecturers over this, I've seen weird stuff like magic properties with format string in objects rather than the UI handling that.

Sign In or Register to comment.