Convert Pixels to CM in WPF

.net, wpf

Solution

As in WPF we deal with DeviceIndependentUnits (DIU, named, conventionally "px"), that units does not depend of the device or screen resolution.

Actually the factors used in .NET Framework (4), for 'px', 'in', 'cm' and 'pt' respectively

// System.Windows.LengthConverter
private static double[] PixelUnitFactors = new double[]
{
    1.0,
    96.0,
    37.795275590551178,
    1.3333333333333333
};

So, we have

private struct PixelUnitFactor
{
    public const double Px = 1.0;
    public const double Inch = 96.0;
    public const double Cm = 37.7952755905512;
    public const double Pt = 1.33333333333333;
}    

public double CmToPx(double cm)
{
    return cm * PixelUnitFactor.Cm;
}

public double PxToCm(double px)
{
    return px / PixelUnitFactor.Cm;
}

Problem

I have ``` ?(New System.Windows.LengthConverter()).ConvertFrom("1cm") 37.795275590551178 {Double} Double: 37.795275590551178 ``` So, in `1cm` I have `37.795275590551178px` WPF pixels. My problem is how I convert back from `px` to `cm`?

Original source

Related problems