在下面的XAML中,按钮将拉伸以适合窗口的宽度,包括在调整窗口大小时.但是,TextBlock和蓝色框居中.你将如何改变它:1)TextBlock在Button内,但左边是实际的Button宽度(即在Window的左侧)2)Canvas在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>
Run Code Online (Sandbox Code Playgroud)
Bah*_*ies 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>
Run Code Online (Sandbox Code Playgroud)
Ham*_*ish 10
您还HorizontalContentAlignment可以Stretch在 Button 本身上设置to 。
这将告诉内容填充按钮上可用的水平空间。
<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>
Run Code Online (Sandbox Code Playgroud)