wpf - 如何获取按钮内容以填充WPF中的宽度

标签 wpf xaml autosize

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

在这种情况下,“Horizo​​ntalAlignment=Stretch”似乎不起作用,并且在使用自动调整大小时,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>

最佳答案

您也可以设置 HorizontalContentAlignmentStretch在按钮本身上。

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

<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>

关于wpf - 如何获取按钮内容以填充WPF中的宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31647009/

相关文章:

c# - WPF TreeView 绑定(bind)

wpf - 在 XAML 中怎么说 : default width and height for e. g。文本框

.net - WPF:如何根据 XAML 中另一个的 Text 属性更改文本框的前景色?

Wpf控制内容大小?

wpf - WPF转换器是如何执行的?

c# - 取决于列表框项目类型的上下文菜单

ios - 自动调整 UI CollectionView 的大小以适应其内容

ios - 如何使 UIPickerView 组件文本始终适合?

c# - 将 System.Windows.Media.Color 绑定(bind)到 TextBlock.Foreground?

c# - XAML 工具提示 + IsHitTestVisible ="False"