I would like to create a C# WPF form that collects measurements of equipment, but some users insit on using feet and inches for measurements while other (younger) users do everything in metric. The database stores everything in meters, and I figured this was a perfect place to use a IMultiValueConverter.
Each form has a DependencyProperty called UseImperialMeasurements that stores the users preference, and I pass this value to the Convert function along with the actual measurement in meters. The code so far looks like this:
<Label>Length:</Label>
<TextBox>
<TextBox.Text>
<MultiBinding Converter="{StaticResource DistanceStringConverter}" Mode="TwoWay">
<Binding Path="Length" />
<Binding ElementName="ThisControl" Path="UseImperialMeasurements" />
</MultiBinding>
</TextBox.Text>
</TextBox>
public class DistanceStringConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (values.Length != 2 || !(values[0] is Double) || !(values[1] is Boolean)) return "ERROR";
Double measurement = (Double)values[0]; // Always in meters
Boolean useImperial = (Boolean)values[1];
string unit;
if (useImperial == true)
{
double feet, inches;
inches = (measurement * 100) / 2.54;
feet = Math.Floor(inches / 12);
inches = inches % 12;
var replacements = new object[4];
replacements[0] = feet.ToString("#,0");
replacements[1] = "'";
replacements[2] = inches.ToString("0");
replacements[3] = "\"";
// Display like 12'4"
return string.Format("{0}{1}{2}{3}", replacements);
}
else
{
// Display like 5,987.97m
return string.Format("{0}{1}", measurement.ToString("#,0.##"), m);
}
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
{
// ToDo: Figure out if imperial or metric measurements are prefered...
}
}
This works well for displaying measurements, but taking them as input in either metric or imperial has been problematic as the I am unable to see the bound value of the UseImperialMeasurements property in the ConvertBack method. As such, I am not only unable to guess if the user is inputing feet or meters when no units are specified, but I have no way to know what boolean value to return so that the users set preference doesn't change.
Is it possible to pass the value of UseImperialMeasurements into the ConvertBack function?