如何在WPF中将宽度设置为100%

75

有没有办法告诉 WPF 中的组件使用所有可用空间?

比如:

width: 100%;  

CSS中:

我有一个XAML代码,不知道如何让Grid宽度占满100%。

<ListBox Name="lstConnections">
  <ListBox.ItemTemplate>
    <DataTemplate>
      <Grid Background="LightPink">
        <Grid.ColumnDefinitions>
          <ColumnDefinition Width="Auto"/>
          <ColumnDefinition Width="Auto"/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
          <RowDefinition Height="Auto"/>
          <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>
        <TextBlock Grid.Row="0" Grid.Column="0" Text="{Binding Path=User}" Margin="4"></TextBlock>
        <TextBlock Grid.Row="0" Grid.Column="1" Text="{Binding Path=Password}" Margin="4"></TextBlock>
        <TextBlock Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="2" Text="{Binding Path=Host}" Margin="4"></TextBlock>
      </Grid>
    </DataTemplate>
  </ListBox.ItemTemplate>
</ListBox>

结果看起来像

alt text http://foto.darth.cz/pictures/wpf_width.jpg

我将它变为粉色以便明显看到它占用了多少空间。我需要使这个粉色网格宽度为100%。


链接已失效... - Martini Bianco
@MartiniBianco,很抱歉,但这个问题已经8年了。我甚至不记得图片里是什么,也自那以后就没有再使用WPF了。 - Jakub Arnold

- Damir Shabayev
3个回答

88

容器Grid的宽度限制了其大小。 在这种情况下,它是ListBoxItem,默认情况下左对齐。 您可以按如下方式将其设置为拉伸:

<ListBox>
    <!-- other XAML omitted, you just need to add the following bit -->
    <ListBox.ItemContainerStyle>
        <Style TargetType="ListBoxItem">
            <Setter Property="HorizontalAlignment" Value="Stretch"/>
        </Style>
    </ListBox.ItemContainerStyle>
</ListBox>

15
小提示 - 如果你想在Windows商店应用程序中执行此操作,你必须使用与上述相同的方法实际设置HorizontalContentAlignment - roryok

70

您可以如下使用HorizontalContentAlignment="Stretch"

<ListBox HorizontalContentAlignment="Stretch"/>

1
对我来说有效的方法是,在一个具有2列和2行的Grid中使用Grid.ColumnSpan="2" Grid.RowSpan="2",使其跨越多列:
<Grid Margin="50">

    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="5*"/>
        <ColumnDefinition Width="4*"/>
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition Height="1*"/>
        <RowDefinition Height="1*"/>
    </Grid.RowDefinitions>
  
    <!-- InputStackPanel -->
    <local:InputStackPanel Grid.ColumnSpan="2" Grid.RowSpan="2" InputsSource="{Binding droppedInputs}"/>

    
</Grid>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接