View or ViewModel duty?
I am building a Maui application where the user can switch between using "kg" or "lbs" across the application.
So the main dilemma I have a Weight property and how to update if the preferred unit has been changed by the user the two ways to update:
Some extra information
I store the weight in kg in the database
there are many collectionviews, also tabbed view so singleton
View with unit converter
For this I could just use MultiBinding to pass the currenct weight value and if currently UseImperialUnits state, ApplicationState is added to the App constructor as resource.
This works so if user switchs the weight unit it updates the ui automatically and calculates the new value for only displaying underhood the Weight property is not changed.
ViewModel
I have a getter property on the ViewModel:
public double Weight => _applicationState.UseImperialUnits ? _model.Weight.ToPounds() : _model.Weight;
In this case for sure I would need to subscribe to the PropertyChange of the UseImperialUnits.ApplicationState so if that changes we need to call:
OnPropertyChanged(nameof(Weight ))
this means in collection I would need to do with all items.
Which approach do you consider best practice in MVVM for handling global unit system preferences?
Do you stick with converters for UI-only scenarios, or do you prefer propagating PropertyChanged through all affected VMs? Any recommended patterns to make this scalable and avoid memory leaks?5 Replies
It is a presentation thing so leave it at the presentation layer. It is same as datetime values. Store them in UTC but when showing to the users (presentation) then convert them to local time. When you move on and want to support even more Weight units only change the presentation. The logic will be untouched
Docs: https://learn.microsoft.com/en-us/dotnet/maui/fundamentals/data-binding/converters?view=net-maui-9.0
Binding value converters - .NET MAUI
Learn how how to cast or convert values within a .NET MAUI data binding by implementing a value converter (which is also known as a binding converter, or binding value converter).
Sorry, I have no clue why you are sending this to me
Just extending your message by docs
@Sir Rufo I would have one more question if you dont mind. What about Entry?
Right now I am using reactive way of viewmodel so when the binded property changed by the entry I am updating the Weight of the model and convert the input if its in lbs to store in kg.
Should this also be solved by controller? So I could use a controller and convert the value to store the equivalent in kg? What do you think about this?
You can see the code below.
I have already the controller ready for Label, i post here maybe its useful for others: