I开发者_如何学JAVA am building an app that can track weight. I allow the user to select their unit preference of kg or lbs. I want to keep the data in the DB standard (kg) so if the user selects lbs as their preference I need the data converted from kg to lbs in the UI.
This conversion can be handled very easily in the ViewModel.
This is one of the huge advantages of having a ViewModel - you can have easily testable logic, such as conversion between units, which stays completely separate from the user interface code.
I suggest you to use it Coverter Property of DataBinding and resolve it by XAML.
DataBinding = { Binding Path = YourProperty,Converter = {StaticResource YourConverter}}
YourConverter must implement the IValueConverter inferface (msdn doc) and has to be declare as Resource.
I would prefer this approach because keep the conversion logic on the View Side.
I'm supposing we are in WPF. Use a Binding Converter and create an object implementing IValueConverter doing the proper configured conversion.
The best way I can explain to do this is to use a custom converter interface. Instead of talking on I'll just zap you an example.
private IConverter<Double, Double> weightConverter = new KgToLbsConverter();
private double _weight;
public double Weight
{
get
{
return weightConverter.ConvertFrom(_weight);
}
set
{
_weight = weightConverter.ConvertTo(value);
RaisePropertyChanged(() => Weight);
}
}
/// <summary>
/// Provides a simple converter contract.
/// </summary>
/// <typeparam name="T">The source Type</typeparam>
/// <typeparam name="R">The target Type.</typeparam>
public interface IConverter<T, R>
{
R ConvertFrom(T value);
T ConvertTo(R value);
}
/// <summary>
/// Provides a converter to change Kg to Lbs and vice versa
/// </summary>
public class KgToLbsConverter : IConverter<Double, Double>
{
/// <summary>
/// From Kg to Lbs.
/// </summary>
/// <param name="value">The weight in Kg.</param>
/// <returns>The weight in Lbs.</returns>
public double ConvertFrom(double value)
{
return value / 2.2;
}
/// <summary>
/// From Lbs to Kg.
/// </summary>
/// <param name="value">The weight in Lbs.</param>
/// <returns>The weight in Kg.</returns>
public double ConvertTo(double value)
{
return value * 2.2;
}
}
Using this you could make can any converters you want, and then let the user select from concrete implementations.
Note: The reason I prefer this over converters is view models may need to know what conversion mode is active and how to work with them, this adds quite a bit of flexibility. When you need a single conversion for a V-VM relationship then IValueConverter is the way to go, but for your scenario, this is easier to maintain and to extend.
精彩评论