如何在WPF中使按钮内容填满整个宽度

19
在以下的XAML中,按钮将会自动伸展以适应窗口的宽度,并且在调整窗口大小时也一样。然而,TextBlock和蓝色方框是居中对齐的。您该如何更改它呢? 1)TextBlock位于Button内部,但是与实际Button宽度左对齐(即在窗口左侧) 2)Canvas位于Button内部,但是与实际Button宽度右对齐(即在窗口右侧)
好像在这种情况下"HorizontalAlignment=Stretch"不起作用,而使用Auto sizing时,Button内部的Grid始终仅增长到其内容所需的最小宽度。
<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>
2个回答

20

你应该设置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>

1
这个有效 - 谢谢!你能解释一下为什么它有效吗? - Denis P
因为当您将元素放置在按钮内(就像您在问题中所做的那样),实际上是设置了“Button.Content”,但您想要做的是更改按钮的布局,这可以通过设置“Button.Template”来实现。 - Bahman_Aries

18
你还可以在按钮上将HorizontalContentAlignment设置为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" 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>

1
这在WinUI中对我有效。如果它在WPF中有效,那么它应该是正确的答案。谢谢。 - Michal Zhradnk Nono3551

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