none
dynamic scale transform

    Question

  • I have a question about using a ScaleTransform in a style. Examining the following line of XAML:

     

    Code Snippet
    <
    ScaleTransform CenterX="?" CenterY="?" ScaleX="0.95" ScaleY="0.95" />

     

     

     

    If the controls which will use this scale transform all vary in size, how do I go about dynamically calculating values for CenterX and CenterY? I would like to do it in XAML if possible but if I am forced to use code behind, where would I write the C# to calculate the property values if the scale transform, which belongs to a style, can be applied to controls throughout the application?

    Thursday, August 09, 2007 5:58 PM

Answers

  •  

    Hi,

     

     You will have to use data binding for your CenterX and CenterY properties, and use a Converter to make the calculation. I often use the following IValueConverter with ScaleTransforms, which takes a double and divides it by two:

    Code Snippet

    /// Divise le double donné par deux

    [ValueConversion(typeof(double), typeof(double))]

    public class DivideDoubleByTwoConverter: IValueConverter

    {

    #region IValueConverter Membres

    ///

    /// Divise par deux un double

    ///

    /// Nombre à diviser par deux

    ///

    ///

    ///

    ///

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)

    {

    if (targetType != typeof(double))

    throw new InvalidOperationException("The target must be a double");

    double d = (double) value;

    return ((double) d )/ 2;

    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)

    {

    throw new NotSupportedException();

    }

    #endregion

    }

     

     

    I then use it from inside my XAML file:

    Code Snippet

    <ScaleTransform

      CenterX="{Binding Path=ActualWidth,

                Converter={StaticResource DivideDoubleByTwoConverter},

                RelativeSource={RelativeSource FindAncestor, Border, 1}}"

      CenterY="{Binding Path=ActualHeight,

                Converter={StaticResource DivideDoubleByTwoConverter},

                RelativeSource={RelativeSource FindAncestor, Border, 1}}"/>

     

    The result is a ScaleTransform that is always centered on the control's center. So if you adapt the IValueConverter, you can basically get any relative CenterX/CenterY you want.

     

    Luc

    Thursday, August 09, 2007 11:09 PM