如何在 xaml WPF 中设置堆栈面板或网格的绝对位置

How can set absolute position on stackpanel or grid in xaml WPF

是否可以将我的 StackPanel 或 Grid 设置为绝对位置,如 CSS。 在 CSS 中有 属性 元素的位置并且可以设置为相对的,绝对的并且工作良好。

在XAML可以让Grid,StackPanel使用position absolute

您必须使用 Canvas 才能在 WPF 中设置绝对位置。

对于 window 中的按钮,这里是一个示例:

<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 的目的,但我同意,有时别无选择,因此您有两个基本选择。

  1. 根网格下的元素
  2. canvas 中与 window 大小相同的元素(正如 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>

试试这个。

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

结果: