5

关于在 a 中定位元素的常见问题Canvas是“如何定位元素的中心(而不是左上角)”。

提出了几种解决方案,但它们都有缺点。

是否有一种简单的(仅限 XAML)方法来定位画布内的元素,以便其Canvas.LeftCanvas.Top对应于元素的中心,并且大小和位置属性都可以绑定到其他一些属性?

我在 WPF 中找到了一种非常简单的方法(只需在 WPFMargin="-1000000" 中仅使用 XAML 设置将 Canvas 内的元素定位在其中心(而不是左上角)),但它不适用于 Silverlight/WinRT . 我知道的唯一其他方法需要创建ValueConverter来执行x *= -0.5计算(这不是仅 XAML)。

4

1 回答 1

2

虽然它并不漂亮,但这里有一个使用RenderTransform不同来源的嵌套 s 来偏移对象的位置以使其居中的示例:

<UserControl x:Class="UrlTest.Center"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    d:DesignHeight="300" d:DesignWidth="400">

    <Canvas x:Name="LayoutRoot" Background="White">
        <ContentControl Canvas.Top="100" Content="{Binding ActualWidth,ElementName=Center, StringFormat=Width \{0\}}"/>
        <ContentControl Canvas.Top="120" Content="{Binding ActualHeight,ElementName=Center, StringFormat=Height \{0\}}"/>
        <Grid x:Name="Center" RenderTransformOrigin="-.5,-.5" Canvas.Left="40" Canvas.Top="25">
            <Grid.RenderTransform>
                <ScaleTransform ScaleX="-1" ScaleY="-1"/>
            </Grid.RenderTransform>
            <Grid RenderTransformOrigin="-.25,-.25">
                <Grid.RenderTransform>
                    <ScaleTransform ScaleX="-1" ScaleY="-1"/>
                </Grid.RenderTransform>
                <Ellipse Width="80" Height="50" Fill="Aquamarine"/>
                <ContentControl FontSize="20" HorizontalContentAlignment="Center" VerticalContentAlignment="Center">Center</ContentControl>
            </Grid>
        </Grid>
    </Canvas>
</UserControl>

内部Grids 用于创建转换,而外部 s 用于Canvas确保其Grid内部将其大小设置为内部内容的大小。

于 2012-11-04T22:14:59.760 回答