Abstract formatting of user interface data

I have several objects that have decimal properties. The properties of these objects are displayed in different places in the interface.

Currently I find myself:

litWeight.Text = person.Weight.ToString("0.00");

      

everywhere. Now I know that in some cases, and I am suspicious of many others, that the client is likely to want 3d.p values. in future.

Is there some template I can use to handle the formatting of this Weight property (and other properties, not just decimal places, maybe dates, etc.) so that I can have this formatting in one place?

I know I can use the string format in webconfig or write some extension methods in the UI, but they don't seem very elegant.

It would be nice to have some formatting objects tied to my objects, so it's inherently obvious which formatter to use.

Thank,

Andrew

+1


source to share


3 answers


The simplest solution would be to make a utility class with static methods that format the various value types appropriately and call them. For example:



litWeight.Text = Utility.FormatWeight(person.Weight);

      

+2


source


Can't you add a method to objects to format the theme? Then each object can delegate the "strategy" object for the actual formatting.

The reason for this is both to be able to change decimal places, etc., and to allow things like internationalization - decimal formatting is locale dependent; some countries use decimal points instead of periods or group numbers in sets other than three, etc.

EDIT: The comment was that the presentation code is displayed at the domain level. True, so apply a standard fix for all design problems; add another layer of indirection :)

You might not want to have full MVC, but the View and Model concept still seems to fit. Maybe define a View class for each object, so the PersonView keeps a reference to the Person object and has properties called format_weight, etc. For every Person property of interest? It should still use the strategy pattern for the actual formatting.



So your example would be

PersonView pv = new PersonView(person)

litWeight.Text = pv.format_weight();

      

(please excuse syntax errors, I don't speak C #)

If you want, could you replace PersonView with replacing Person by overriding the methods / properties and delgating to the specified Person, or inheriting from Person when creating the PersonView?

+1


source


You can create a very simple custom control - originating from a label or similar - that is solely responsible for displaying the weight string, so you have:

weightValue.DisplayValue(person.Weight);

      

and the setter formats the decimal value as needed. If this is used when you are showing a weight, you need to change the custom control to change all of the weight displays.

The basic version can be:

public void DisplayValue(decimal weight)
{
    this.Text = weight.ToString("0.00");
}

      

+1


source







All Articles