2016-10-18 30 views
1

我想用它的ListBoxItem來拉伸ListBox。擴展ListBox本身不是問題。問題似乎是告訴ListBoxItem使用ListBox中的可用空間。UWP中的Strech ListBox和ListBoxItems

<Page.Content> 
    <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}" Height="200"> 
     <ListBox VerticalContentAlignment="Stretch" VerticalAlignment="Stretch" Background="Green" ItemsSource="{x:Bind Path=ChessFieldList}" > 
      <ListBox.ItemTemplate> 
       <DataTemplate > 
        <StackPanel HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Background="Yellow" BorderBrush="Red" BorderThickness="3" > 
        </StackPanel> 
       </DataTemplate> 
      </ListBox.ItemTemplate> 
     </ListBox> 
    </Grid> 
</Page.Content> 

下圖顯示了上述和預期結果。

enter image description here

我怎樣才能達到預期的效果?

[編輯]的其他在我看來正確的解決方案:Set Width and Height of ItemsControl Children

+0

可能的[UWP列表框/ ItemsControl]重複(http://stackoverflow.com/questions/40094115/strech-listbox-itemscontrol-in-uwp) – AVK

+0

沒有關於拉伸列表框 - 這一個關於streching listboxitems – Briefkasten

回答

1

這是一個常見的問題。所有你需要做的是設置ListBoxItemHorizontalContentAlignment太:

<ListBox Background="Green" ItemsSource="{x:Bind ChessFieldList}"> 
    <ListBox.ItemTemplate> 
     <DataTemplate> 
      <StackPanel Background="Yellow" BorderBrush="Red" BorderThickness="3" Height="50"> 
      </StackPanel> 
     </DataTemplate> 
    </ListBox.ItemTemplate> 
    <ListBox.ItemContainerStyle> 
     <Style TargetType="ListBoxItem"> 
      <Setter Property="HorizontalContentAlignment" Value="Stretch"/> 
     </Style> 
    </ListBox.ItemContainerStyle> 
</ListBox> 

由於StackPanel不包含任何內容,它不會有任何的高度,所以我剛剛加入Height="50"給它這個演示的目的。

+0

我試圖用一個網格替換Stackpanel,這樣就不需要顯式的Height值。但這似乎不起作用。沒有設置高度,沒有解決方案嗎? – Briefkasten

+1

@Briefkasten沒有任何子元素的網格具有零高度。 – Clemens

+0

@Clemens我用作DataTemplate中: <網格背景= 「黃色」 BorderBrush = 「紅」 了borderThickness = 「3」> <邊框背景= 「米色」 CornerRadius = 「20」> Briefkasten

0

只需添加

<ListBox.ItemContainerStyle> 
    <Style TargetType="ListBoxItem"> 
     <Setter Property="HorizontalContentAlignment" Value="Stretch"/> 
    </Style> 
</ListBox.ItemContainerStyle> 

如果使用分組,您應該包括:

<ListView.GroupStyle> 
    <GroupStyle HidesIfEmpty="False"> 
     <GroupStyle.HeaderContainerStyle> 
      <Style TargetType="ListViewHeaderItem"> 
       <Setter Property="HorizontalContentAlignment" Value="Stretch" /> 
       <Setter Property="VerticalContentAlignment" Value="Stretch" /> 
      </Style> 
     </GroupStyle.HeaderContainerStyle> 
    </GroupStyle> 
</ListView.GroupStyle> 

這是多一點比你要求的,但它是一個鮮爲人知的技術。