XAML: Using IValueConverter to convert metric to imperial

Viewed 568

So I have some XAML that allows a user to control a slider to input their height. I then have a label bound to this value to show them the decimal value of the slider. This is the metric value (cm) so I show the simple number:

<Label Text="Height (cm):" HorizontalTextAlignment="Start" />
<StackLayout x:Name="HeightSliderContainer">
    <Slider x:Name="HeightSlider" Maximum="250" Minimum="100" Value="175" />
    <Label x:Name="HeightSliderLabel" BindingContext="{x:Reference HeightSlider}" Text="{Binding Value, StringFormat='{0:F0}'}" />
</StackLayout>

And this works well. I now want to add in the imperial conversion alongside this number to show the height in feet/inches for those old school users. So I wrote a Converter that implements IValueConverter and this works well, taking in the value of the slider (double) and returning a string in the format "5ft 10in" for example. However, I can't get this value to render in my XAML, I'm getting nothing but an empty string for the label:

<Label Text="Height (cm):" HorizontalTextAlignment="Start" />
<StackLayout x:Name="HeightSliderContainer">
    <Slider x:Name="HeightSlider" Maximum="250" Minimum="100" Value="175" />
    <Label x:Name="HeightSliderLabel" BindingContext="{x:Reference HeightSlider}" Text="{Binding Value, StringFormat='{0:F0}'}" />
    <Label Text="(" />
    <Label x:Name="HeightSliderLabelImperial" BindingContext="{x:Reference HeightSlider}" 
           Text="{Binding Value, Converter={StaticResource MetricToImperialHeightTypeConverter}}" />
    <Label Text=")" />
</StackLayout>

So the output is just:

150 ()

rather than

150 (4ft 11in)

Is there something I need to add to my XAML to get it to render the returned string? I've stepped through my IValueConverter and confirmed it is returning a string with the correct data when called.

Thanks

Edit:

Should also have added that on another page, where there is no slider, I am just displaying the saved value, I have the following:

<Label x:Name="HeightLabelImperial" Text="{Binding User.HeightInCm,
Converter={StaticResource MetricToImperialHeightTypeConverter}}" />

And this works correctly, displaying the height as "4ft 11in" for example, so its something to do with the bindingcontext and the value being fed by the slider, or so I'm inclined to think.

Edit2:

Conversion code:

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        int cm = 0, feet = 0, inches = 0;
        cm = System.Convert.ToInt32((double)value);
        UnitConverter.CMToFeetAndInches(cm, out feet, out inches);

        string result = $"{feet}ft {inches}in";

        return result;            
    }
0 Answers
Related