bsh152s bsh152s - 4 years ago 127
C# Question

WPF binding/display of different units

I have an application that needs to display a lot of values in different units (feet vs. meters, degrees vs. radians, miles vs. kilometers, etc). Each displayed value needs to have its own selectable unit (feet or meters). My first thought is creating a user control with just a text box for the display of the value and a combo box for the available units.

But, how do I work the binding of the text box so that the right unit is displayed? And, how do I work the binding of the text box so that if the value is changed, the value of the correct underlying model type (feet or meters) gets stored?

UPDATE:

I ended up using the MultConverter as @Sledgehammer had suggested. I added a format string so developer can control that too.

Within FeetToMetersMultiValueConverter : IMultiValueConverter

public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
double value = (double)values[0];
FeetOrMetersSelectionType valueType = (FeetOrMetersSelectionType)values[1];
FeetOrMetersSelectionType displayValueType = (FeetOrMetersSelectionType)values[2];
string valueFormat = (string)values[3];

if (valueType != displayValueType)
{
if (displayValueType == FeetOrMetersSelectionType.Meters)
{
value = value * 0.3048;
}
else
{
value = value / 0.3048;
}
}

return value.ToString(valueFormat);
}

Answer Source

You can use a MultiBinding on the text box. Pass in the Text and Units to the MultiConverter and have it do the calculations and return the text.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download