如何在XAML WPF中的StackPanel或Grid上设置绝对位置

18

我能否把我的 StackPanel 或 Grid 设置成像 CSS 一样的绝对定位呢?在 CSS 中,元素有一个 Position 属性,可以设置为相对定位、绝对定位,而且效果很好。

在 XAML 中,也可以让 Grid 和 StackPanel 使用绝对定位。


你能详细说明一下你所说的“absolute”是什么意思吗?你是指相对于窗口的绝对位置吗?否则,结合使用MarginHorizontalAlignmentVerticalAlignment应该可以实现你想要的效果。 - Geoffrey
是的,相对于窗口的绝对位置。 - somePeaple
3个回答

29

为了在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>
输出结果为:

enter image description here

如需要帮助,请随时询问。

我怎样在画布中设置绝对位置以适应窗口? - somePeaple
回答已编辑,请不要忘记标记我的答案为“已确认”,如果对您有帮助。 - Vasilievski
好的,谢谢你的回答。我没有忘记,只是在思考可能会出现的问题,因为这只是问题的一小部分。 - somePeaple
而且,如果您认为问题很好,请不要忘记检查它是否有用和清晰。 - somePeaple

4

绝对定位违背了WPF的初衷,但我同意,有时候没有其他办法,所以你有两个基本选项:

  1. 根网格下的元素
  2. 与窗口大小相同的画布中的元素(正如Vasilievski所指出的那样)

代码示例:

<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>

8
绝对定位并不违背 WPF 的设计初衷,我认为您对该术语存在误解。 - Ryan
@Ryan 我同意,特别是图形丰富的场景。 - StayOnTarget
是的,绝对定位是正确的方法。最终我可以将控件放置在我想要的位置,而不是它们跳到愚蠢的地方。此外,请参阅此问题以了解如何在代码后台中进行设置。https://dev59.com/X2Ei5IYBdhLWcg3wMp9y - Paul McCarthy

0

试试这个。

<StackPanel>
   <Canvas>
      <TextBlock Canvas.Left="10" Canvas.Top="6" Text="Choose a value from combobox:" Width="180"/>
      <ComboBox Canvas.Left="190" Canvas.Top="4" Width="180"></ComboBox>
   </Canvas>
</StackPanel>

结果:

enter image description here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接