How can I create an Image Reflection in WPF without having to hard-code the width and height?

Reflecting another visual in WPF is typically done using a VisualBrush and a ScaleTransform to “flip” the content upside down, as shown in this nice example on xamlog. In order to perform the “flip” the ScaleTransform needs the centre about which this should occur. Unfortunately the centre position of an element is not directly exposed via a property, so the net result of this is that for simple reflections (where you know the size of the source) you typically end up hard-coding the centre of the transform in your XAML . A recent poster in the WPF forums asked if it was possible to avoid this hard-coding. One approach which I’m going to explore here is to use data binding and a fairly generalized “arithmetic converter” capable of multiplying, dividing, adding to or subtracting from values as part of the binding operation . In order to obtain the center for our ScaleTransform we bind the CenterX property of the transform to the ActualWidth of the element we want to reflect, and multiply by 0.5. Similarly we can bind the CentreY property of the transform to the ActualHeight * 0.5. The arithmetic operation is specified to the converter using the ConverterParameter property of the binding. In order to use the converter we first need to add a namespace alias to the CLR namespace that the converter is contained in.

<Window x:Class=“LearnWPF.ReflectionWithoutHardCodingWidth.Window1”
    xmlns=”
http://schemas.microsoft.com/winfx/2006/xaml/presentation
    xmlns:x=”
http://schemas.microsoft.com/winfx/2006/xaml
    xmlns:cvrt=“clr-namespace:LearnWPF.Converters”
    Title=“LearnWPF.ReflectionWithoutHardCodingWidth” Height=“300” Width=“300”
    >
Then we can use the converter like so to perform the binding.

<ScaleTransform ScaleX=“1” ScaleY=“-1”
    CenterX=“{Binding ElementName=PhotoBorder,
                      Path=ActualWidth,
                      Converter={StaticResource arithConverter},
                      ConverterParameter=*0.5}”

    CenterY=“{Binding ElementName=PhotoBorder,
                      Path=ActualHeight,
                      Converter={StaticResource arithConverter},
                      ConverterParameter=*0.5}”
/>

This generalized arithmetic converter is clearly over-engineered for the task of finding the centre of an element, but it has other applications when using bindings to control layout in WPF.
I’ve created a complete project, using the sample from Xamlog as a starting point which you can download here. Below are screen-shots of the reflection in action with images of different sizes and aspect ratios.