1

I have an Image inside a Canvas:

<Canvas>
    <Image HorizontalAlignment="Center" VerticalAlignment="Center" />
</Canvas>

And I want to display the Image always (even after a possible resizing) in the center of my Canvas, but in this way the image is draw in the Top-Left corner. How can I do?

4

2 回答 2

8

The coolest thing of this aproach taht it would work if you change sizes of both image and canvas. Converter code:

internal sealed class CenterConverter : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        double canvasWidth = System.Convert.ToDouble(values[0]);
        double canvasHeight = System.Convert.ToDouble(values[1]);
        double controlWidth = System.Convert.ToDouble(values[2]);
        double controlHeight = System.Convert.ToDouble(values[3]);
        switch ((string)parameter)
        {
            case "top":
                return (canvasHeight - controlHeight) / 2;
            case "bottom":
                return (canvasHeight + controlHeight) / 2;
            case "left":
                return (canvasWidth - controlWidth) / 2;
            case "right":
                return (canvasWidth + controlWidth) / 2;
            default:
                return 0;
        }
    }

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

XAML, somewhere in resources:

    <local:CenterConverter x:Key="CenterConverter" />

XAML:

<Canvas x:Name="superCoolCanvas">
    <Image x:Name="superCoolImage" >
        <Canvas.Top>
            <MultiBinding Converter="{StaticResource CenterConverter}" ConverterParameter="top">
                <Binding ElementName="superCoolCanvas" Path="ActualWidth" />
                <Binding ElementName="superCoolCanvas" Path="ActualHeight" />
                <Binding ElementName="superCoolImage" Path="ActualWidth" />
                <Binding ElementName="superCoolImage" Path="ActualHeight" />
            </MultiBinding>
        </Canvas.Top>
        <Canvas.Left>
            <MultiBinding Converter="{StaticResource CenterConverter}" ConverterParameter="left">
                <Binding ElementName="superCoolCanvas" Path="ActualWidth" />
                <Binding ElementName="superCoolCanvas" Path="ActualHeight" />
                <Binding ElementName="superCoolImage" Path="ActualWidth" />
                <Binding ElementName="superCoolImage" Path="ActualHeight" />
            </MultiBinding>
        </Canvas.Left>
    </Image>
</Canvas>
于 2012-06-21T22:19:46.087 回答
2

Canvas is intended to use absolute coordinates. You may use solution provided by dwrd or put Canvas and Image both in Grid and then center the Image in this Grid.

于 2012-06-22T03:17:27.683 回答