如何让按钮内容填充WPF中的宽度

How to get button content to fill width in WPF

在下面的 XAML 中,按钮将拉伸以适合 window 的宽度,包括在您调整 window 大小时。但是,TextBlock 和蓝色框居中。你会如何改变它,以便: 1) TextBlock 位于 Button 内部,但与实际 Button 宽度左对齐(即在 Window 的左侧) 2) Canvas 在 Button 内部,但与实际 Button 宽度右对齐(即在 Window 的右侧)

似乎 "HorizontalAlignment=Stretch" 在这种情况下不起作用,而且,当使用自动调整大小时,按钮内的网格只会增长到其内容所需的最小宽度。

<Window
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    x:Name="Window"
    Title="test"
    Width="640" Height="480">

    <Grid x:Name="LayoutRoot">
        <Button Height="30">
            <Grid HorizontalAlignment="Stretch">
                <TextBlock Text="Sample Text" HorizontalAlignment="Stretch" TextAlignment="Left"></TextBlock>
                <Canvas Width="40" Background="AliceBlue" HorizontalAlignment="Right"></Canvas>
            </Grid>
        </Button>
    </Grid>
</Window>

你应该设置Button.Template。也可以用Grid.ColumnDefinitions来适当设置里面元素的位置和宽度。

        <Button Height="30" Content="Smaple text">
            <Button.Template>
                <ControlTemplate TargetType="{x:Type Button}">
                    <Grid>
                        <Border Background="{TemplateBinding Background}"
                         BorderBrush="{TemplateBinding BorderBrush}"
                         BorderThickness="{TemplateBinding BorderThickness}">
                            <Grid>
                                <Grid.ColumnDefinitions>
                                    <ColumnDefinition Width="Auto"/>
                                    <ColumnDefinition Width="*"/>
                                </Grid.ColumnDefinitions>
                                <ContentPresenter HorizontalAlignment="Left"  Grid.Column="0"
                                          VerticalAlignment="Center"/>
                                <Canvas Background="AliceBlue" Grid.Column="1" />
                            </Grid>
                        </Border>
                    </Grid>
                </ControlTemplate>
            </Button.Template>
        </Button>

您还可以将按钮本身的 HorizontalContentAlignment 设置为 Stretch

这将告诉内容填充按钮上可用的水平 space。

<Window
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    x:Name="Window"
    Title="test"
    Width="640" Height="480">

    <Grid x:Name="LayoutRoot">
        <Button Height="30" HorizontalContentAlignment="Stretch">
            <Grid HorizontalAlignment="Stretch">
                <TextBlock Text="Sample Text" HorizontalAlignment="Stretch" TextAlignment="Left"></TextBlock>
                <Canvas Width="40" Background="AliceBlue" HorizontalAlignment="Right"></Canvas>
            </Grid>
        </Button>
    </Grid>
</Window>