Sunday, June 21, 2015

XAML Celsius Fahrenheit converter (no code behind)

Ever wanted to convert Celsius to Fahrenheit in your WPF application, without any code behind?

Here is how you do it, using a trick I learnt from Charles Petzold.

<DockPanel>

 <FrameworkElement Name="calcC2F" Visibility="Collapsed">
   <FrameworkElement.RenderTransform>
     <TransformGroup>
       <TranslateTransform X="{Binding ElementName=sldr, Path=Value}" />
         <ScaleTransform ScaleX="1.8" />
          <TranslateTransform X="32" />
         </TransformGroup>
        </FrameworkElement.RenderTransform>
       </FrameworkElement>
        
  <Slider Name="sldr" Minimum="-100" Maximum="100" TickFrequency="1"            IsSnapToTickEnabled="True" Value="0" Margin="5" DockPanel.Dock="Top"/>
        
  <DockPanel>

    <TextBlock Text="{Binding ElementName=sldr,Path=Value, StringFormat={}{0}°C}" FontSize="36" DockPanel.Dock="Top" HorizontalAlignment="Center"/>
      
    <TextBlock Text="{Binding ElementName=calcC2F, Path=RenderTransform.Value.OffsetX, StringFormat={}{0}°F}" 
FontSize="36" HorizontalAlignment="Center"/>
        
  </DockPanel>

 </DockPanel>




You can apply this principle to many occasions when you need to calculate something in XAML without having to resort to code behind!