【问题标题】:Positioning an element inside the Canvas by its center (instead of the top left corner) using only XAML in Silverlight/WinRT在 Silverlight/WinRT 中仅使用 XAML 将元素定位在画布内的中心(而不是左上角)
【发布时间】:2012-10-24 13:12:02
【问题描述】:

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

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

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

我在 WPF 中找到了一种非常简单的方法(只需设置 Margin="-1000000" Positioning an element inside the Canvas by its center (instead of the top left corner) using only XAML in WPF),但它不适用于 Silverlight/WinRT。我知道的唯一其他方法需要创建 ValueConverter 来执行 x *= -0.5 计算(这不是 XAML-only)。

【问题讨论】:

    标签: silverlight xaml canvas windows-runtime centering


    【解决方案1】:

    虽然不是很漂亮,但这里有一个示例,使用具有不同原点的嵌套 RenderTransforms 来偏移对象的位置以使其居中:

    <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 用于创建转换,而外部Canvas 用于确保其内部的Grid 将其大小设置为内部内容的大小。

    【讨论】:

    • 相当巧妙!我试图解决几个变换方程的系统以得出这样的解决方案,但失败了。这些双重变换很好地完成了交易。附言RenderTransformOrigin 值也可以是0,00.25,0.25-0.25,-0.250,0。他们只需要满足Internal - External = 1/4 方程。
    猜你喜欢
    • 2012-10-24
    • 1970-01-01
    • 2016-07-12
    • 1970-01-01
    • 2017-11-30
    • 1970-01-01
    • 2015-11-22
    • 1970-01-01
    • 2018-03-20
    相关资源
    最近更新 更多