在下面的XAML中,按钮将拉伸以适合窗口的宽度,包括在调整窗口大小时。但是,TextBlock和蓝色框居中。你会如何改变它: 1)TextBlock在Button内,但左对齐实际的Button宽度(即在Window的左侧) 2)Canvas在Button内部,但与实际的Button宽度右对齐(即在窗口的右侧)
似乎“HorizontalAlignment = 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>
答案 0 :(得分: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>
答案 1 :(得分:0)
您还可以在按钮本身上将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>