XAML:当我明确地说要在底部时,为什么按钮在顶部?

标签 xaml

在 XAML 中,我希望按钮位于红色矩形的底部。

我明确地说:

“水平对齐=右”
VerticalAlignment="底部"

它会向右移动,但仍位于顶部。这是为什么?

alt text http://tanguay.info/web/external/buttonTop.png

<UserControl
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    x:Class="MultiplePages.Page"
    Width="300" Height="150">

    <StackPanel HorizontalAlignment="Stretch" 
        VerticalAlignment="Stretch" Width="300" Height="150" Orientation="Vertical">

        <StackPanel Width="300" Height="100" Background="Blue">
            <TextBlock x:Name="theTextBlock" Text="This is page one. This is page one. This is page one. This is page one. This is page one. This is page one. This is page one. This is page one. This is page one. This is page one. " 
            TextWrapping="Wrap" Height="100" Width="300" HorizontalAlignment="Left"/>
        </StackPanel>

        <StackPanel Width="300" Height="50" Background="Red">

            <Button Name="Switch" Content="Switch Page" Width="100" Height="20"
            HorizontalAlignment="Right" 
            VerticalAlignment="Bottom"/>

        </StackPanel>

    </StackPanel>

</UserControl>

最佳答案

StackPanel 旨在根据其元素和容器(取决于其方向)获取其大小,尽管您所做的看起来是正确的,但这并不是 StackPanel“应”使用的方式。虽然它看起来像是设置的高度,但它的实际高度(用于布局子控件)是其内容(按钮)的大小。 StackPanel 有它的用途,但如果您要做的不仅仅是简单的控件堆栈,那么您通常应该使用其他东西。

您可以通过在里面粘贴一个大小合适的网格来修复它:

<StackPanel Width="300" Height="50" Background="Red">
          <Grid Height="50">
            <Button Name="Switch" Content="Switch Page" Width="100" Height="20"
            HorizontalAlignment="Right" VerticalAlignment="Bottom"
            />
          </Grid>
        </StackPanel>

或者,对于该特定布局,您可能需要查看 DockPanel,它的行为更像您所期望的。

关于XAML:当我明确地说要在底部时,为什么按钮在顶部?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/498961/

相关文章:

c# - 从两种颜色(从渐变)计算中间色

c# - WPF DatePicker,显示今天的日期并绑定(bind)到属性

c# - 忽略特定控件及其子控件的全局样式

wpf - XAML - 使用来自另一个程序集的资源字典中的字体

c# - 独立于分辨率的 WPF 应用程序

c# - 如何绑定(bind)到 Silverlight 中的页面属性?

c# - UWP:- 拖动项目时如何创建拖动 UI(指示要放置项目的位置)?

c# - 相对源绑定(bind) Xamarin

c# - Win 8 RT路由参数

c# - XAML DataTemplate 数据绑定(bind)