ListBox中的项目无法正确拉伸

时间:2011-11-03 00:59:43

标签: wpf xaml listbox listboxitem stretch

检查此xaml:

<Window
  x:Class="MainWindow"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:sys="clr-namespace:System;assembly=mscorlib"
  Width="300">
  <ListBox HorizontalContentAlignment="Stretch"
      Grid.IsSharedSizeScope="True">
    <ListBox.ItemsSource>
      <x:Array Type="{x:Type sys:Int32}">
        <sys:Int32>25</sys:Int32>
        <sys:Int32>10</sys:Int32>
        <sys:Int32>50</sys:Int32>
        <sys:Int32>30</sys:Int32>
        <sys:Int32>80</sys:Int32>
      </x:Array>
    </ListBox.ItemsSource>
    <ListBox.ItemContainerStyle>
      <Style TargetType="ListBoxItem"
           BasedOn="{StaticResource {x:Type ListBoxItem}}">
        <Setter Property="HorizontalContentAlignment" Value="Stretch" />
      </Style>
    </ListBox.ItemContainerStyle>
    <ListBox.ItemTemplate>
      <DataTemplate>
        <Grid Background="#FFE41515">
          <Grid.ColumnDefinitions>
            <ColumnDefinition SharedSizeGroup="name" Width="Auto"/>
            <ColumnDefinition SharedSizeGroup="value"/>
          </Grid.ColumnDefinitions>

          <TextBlock Text="Value:"/>
          <ProgressBar
              Value="{Binding Mode=OneWay}"
              Grid.Column="1" 
              HorizontalAlignment="Stretch"
              HorizontalContentAlignment="Stretch"/>
        </Grid>
      </DataTemplate>
    </ListBox.ItemTemplate>
  </ListBox>
</Window>

这是输出,注意ProgressBar没有拉伸,为什么?
如果项目是红色,则表示每个项目填满整个宽度,那么为什么ProgressBar不伸展? enter image description here

1 个答案:

答案 0 :(得分:4)

如果您只有SharedSizeGroups,则永远不会占用剩余空间,它们的行为类似于Width="Auto"(大小与内容),并且具有最大项目的限制。由于你只有两列你甚至不需要两个这样的组,因为第二列在每个项目中已经是相同的宽度,对吗?

相反如何:

  <Grid.ColumnDefinitions>
    <ColumnDefinition SharedSizeGroup="name" Width="Auto"/>
    <ColumnDefinition /> <!-- Implicit: Width="*" -->
  </Grid.ColumnDefinitions>