我能否把我的 StackPanel 或 Grid 设置成像 CSS 一样的绝对定位呢?在 CSS 中,元素有一个 Position 属性,可以设置为相对定位、绝对定位,而且效果很好。
在 XAML 中,也可以让 Grid 和 StackPanel 使用绝对定位。
为了在WPF中设置绝对位置,您需要使用Canvas
。
对于窗口中的按钮,这是一个示例:
<Window x:Class="tobedeleted.MainWindow"
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"
Title="MainWindow" Height="350" Width="525">
<Canvas>
<Button Canvas.Left="10" Canvas.Bottom="20">Bottom left</Button>
</Canvas>
</Window>
输出结果为:
如需要帮助,请随时询问。绝对定位违背了WPF的初衷,但我同意,有时候没有其他办法,所以你有两个基本选项:
代码示例:
<Window x:Class="WpfApplication1.Window3"
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"
xmlns:local="clr-namespace:WpfApplication1"
mc:Ignorable="d"
Title="Window3" Height="300" Width="300">
<Grid>
<Rectangle Fill="Red" Width="100" Height="120"
HorizontalAlignment="Left"
VerticalAlignment="Top"
Panel.ZIndex="13"
Margin="12,34"
/>
<Rectangle Fill="Green" Width="100" Height="120"
HorizontalAlignment="Left"
VerticalAlignment="Top"
Margin="24,54"
/>
<Canvas>
<Rectangle Canvas.Left="5" Canvas.Top="5" Panel.ZIndex="2" Fill="Yellow" Width="120" Height="30" />
<Rectangle Canvas.Left="25" Canvas.Top="17" Panel.ZIndex="0" Fill="Blue" Width="120" Height="30" />
</Canvas>
</Grid>
</Window>
Margin
、HorizontalAlignment
和VerticalAlignment
应该可以实现你想要的效果。 - Geoffrey