关于在 Canvas 中定位元素的常见问题是“如何定位元素的中心(而不是左上角)”。
- WPF: Resizing a circle, keeping the center point instead of TopLeft?
- WPF Center Ellipse at X, Y
- WPF element positioning on a Canvas
提出了几种解决方案,但它们都有缺点。
是否有一个简单的(仅 XAML)方法可以将元素定位在 Canvas 内,以便其 Canvas.Left
和 Canvas.Top
对应于元素的center AND 大小和位置属性可以绑定(bind)到其他一些属性吗?
我在 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)。
最佳答案
虽然它不太漂亮,但下面是一个使用不同原点的嵌套 RenderTransform 来偏移对象位置以使其居中的示例:
<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>
内部的Grid
用于创建变换,而外部的Canvas
用于确保其内部的Grid
设置其大小与其内部内容的大小相同。
关于silverlight - 在 Silverlight/WinRT 中仅使用 XAML 将元素定位在 Canvas 内的中心(而不是左上角),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13219591/