Question

Im designing my app models and started wondering, is there any general thumb rule when I should use formatted properties and when IValueConverters?

For example I have model like this:

public interface IFlight
{
  DateTime ArrivalTime { get; }
  TimeSpan Duration { get; }
  int LengthMeters{ get; }
}

I have list of Flight items, I can use IValueConverters to display ArrivalTime formatted to only time, Duration formatted to only hours, Length formatted to miles.

Another way to do this is:

 public interface IFlight
{
    DateTime ArrivalTime { get; }
    string ArrivalTimeFormatted { get; }

    TimeSpan Duration { get; }
    string DurationFormatted { get; }

    int LengthMeters{ get; }
    string LengthFormatetd{ get; }
}

Now I can just bind ArrivalTimeFormatted, DurationFormatted and LengthFormatetd to my view. This makes view (xaml) cleaner but models little more complicated.

So which one is generally better approach? Hopefully this is not too general question.

Was it helpful?

Solution

I think it always comes down to personal reference.

Usually, i use formatters with types such as string and datetim where i just want them to be printed on the UI in a pretty way.

With ValueConverters i usually take a totally different approach. A common ValueCnverter i often see if BooleanToVisibillityConverter where you have some bool which decides whether a control will be displayed or not. generally when you want have some property which decides whether some actions will execute or not but you cannot use that property in a straight forward way with Binding.

I hope that made sense :)

OTHER TIPS

If you following the MVVM pattern, it would be the first way. by defining the formatting in the code you are setting the display parameters as a fixed system. using the value converter allows you to change the display in xaml by changing which converter you are using freeing up the view layer to device how to view. ie perhaps you would like custom converters for different countries.

I would say it depends on the app. If it is a quick and dirty POC then do it in IFlight. If you want something that will be more maintainable and reusable I would use a value converter as this will surely will not be the only place this formatting logic will be useful.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top