如何在WPF中获取按钮内容以填充宽度

问题描述 投票:7回答:2

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

似乎“Horizo​​ntalAlignment = Stretch”在这种情况下不起作用,并且,当使用自动调整大小时,Button内的网格只会增长到其内容所需的最小宽度。

<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>
wpf xaml autosize
2个回答
12
投票

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

0
投票

您还可以在Button本身上将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>
© www.soinside.com 2019 - 2024. All rights reserved.