Cast of a Double value to a Single in {x:Bind}

Viewed 113

I'm porting code that was using the {Binding} markup extension to the more modern {x:Bind} and face the following error when building my project:

Cannot directly bind type 'System.Double' to 'System.Single'. Use a cast, converter or function binding to change the type

My code is the following:

            <Grid>
                <TextBlock Text="Rotation"
                       Rotation="{x:Bind slider.Value}"
                       x:DefaultBindMode="OneWay"
                       FontWeight="Bold"
                       FontSize="36"
                       HorizontalAlignment="Center"
                       VerticalAlignment="Center" />

                <Slider x:Name="slider"
                        Maximum="360"
                        VerticalAlignment="Stretch" />
            </Grid>

I can see that Slider.Value is defined as a Double where TextBlock.Rotation is a float. What's the correct way to cast slider.Value to a Single?

I tried casting like this {x:Bind (x:Single)slider.Value} but the build then fails with the error:

Invalid binding path '(x:Single)slider.Value' : Type 'x:Single' not found.
1 Answers

I found a solution: importing the namespace System in my XAML file. Though I'm not sure if that's a good approach.

<Page x:Class="TodoUWP.MainPage"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
      mc:Ignorable="d"
      xmlns:sys="using:System"
    > <!--  here import `System` namespace -->

    <Grid>
        <TextBlock Text="Rotation"
                   x:DefaultBindMode="OneWay"
                   FontWeight="Bold"
                   FontSize="36"
                   HorizontalAlignment="Center"
                   VerticalAlignment="Center"
                   Rotation="{x:Bind (sys:Single)slider.Value}" />
                   <!--                                                 -->
                   <!-- then cast with `sys:Single` instead of `x:Single` -->

        <Slider x:Name="slider"
                Maximum="360"
                VerticalAlignment="Stretch" />
    </Grid>

</Page>

I'm still not sure why x:Single isn't valid, Visual Studio does auto-complete for it.

Related