How to get button content to fill width in WPF

后端 未结 2 582
面向向阳花
面向向阳花 2020-12-19 01:52

In the following XAML the button will stretch to fit the width of the window, including as you resize the window. However, the TextBlock and blue box are centered. How wou

相关标签:
2条回答
  • 2020-12-19 02:15

    You could also set the HorizontalContentAlignment to Stretch on the Button itself.

    This will tell the content to fill the horizontal space available on the 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" 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>
    
    0 讨论(0)
  • 2020-12-19 02:20

    You should set Button.Template. Also Grid.ColumnDefinitions can be used to set the position and width of elements inside properly.

            <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 讨论(0)
提交回复
热议问题