在以下 XAML 中,按钮将拉伸(stretch)以适应窗口的宽度,包括在调整窗口大小时。但是,TextBlock 和蓝色框居中。你会如何改变它,以便:
1) TextBlock 位于 Button 内部,但与实际 Button 宽度左对齐(即在 Window 的左侧)
2) Canvas 位于 Button 内部,但与实际 Button 宽度右对齐(即在 Window 的右侧)
在这种情况下,“HorizontalAlignment=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>
最佳答案
您也可以设置 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>
关于wpf - 如何获取按钮内容以填充WPF中的宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31647009/