【问题标题】:Items in ListBox don't stretch properlyListBox 中的项目不能正确拉伸
【发布时间】:2011-11-03 00:59:43
【问题描述】:

检查这个 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 没有拉伸??

【问题讨论】:

    标签: wpf xaml listbox listboxitem stretch


    【解决方案1】:

    如果你只有SharedSizeGroups,其余空间永远不会被占用,它们总是表现得像Width="Auto"(大小到内容),并受到最大项目的限制。由于您只有两列,您甚至不需要两个这样的组,因为第二个在每个项目中的宽度已经相同,对吧?

    这个怎么样:

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

    【讨论】:

    • @Shimmy:很高兴有帮助:)
    • 顺便说一句 F1 是你的敌人,它只会分散注意力,你的朋友是谷歌,所以......
    • @Shimmy:如果您使用 VS 2010,它是您的朋友,您可以直接访问光标所在的文档,无论是类、属性、方法还是其他任何东西。顺便说一句,你在奇怪的时候编码:P
    • @B.H.我确实喜欢 标签。如果这是奇怪的时期,你现在在做什么?但现在是凌晨 03:46 并不奇怪,这是编码的最佳时间,编码的时间!
    • @Shimmy:好吧,我正要上床睡觉,但我同意,现在是编码的好时机,但我不知道有多少人会同意这种观点。
    猜你喜欢
    • 2017-02-27
    • 1970-01-01
    • 2017-02-26
    • 2022-01-12
    • 1970-01-01
    • 2015-11-11
    • 1970-01-01
    • 2012-10-19
    • 1970-01-01
    相关资源
    最近更新 更多