Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make the StackPanel or DockPanel stretch to fit their containers in WPF?

Tags:

wpf

I have a Grid as a root container with two columns defined (There's only one row).
The first column has flexible width and second column has 300px fixed width.
Next, I have placed a ListBox inside the second column to stretch both horizontally and vertically, i.e. to fill the entire second column.
Lastly, I have defined an Items Template for the ListBox to be a vertically oriented StackPanel, with one DockPanel and a couple of TextBlocks inside.

<!-- Data template for ListBox -->
<DataTemplate DataType="{x:Type entities:Track}">
  <StackPanel Orientation="Vertical">
    <DockPanel>
      <TextBlock DockPanel.Dock="Left" Text="Now playing" />
      <TextBlock DockPanel.Dock="Right" Text="Time remaining" />
    </DockPanel>
    <TextBlock Text="{Binding Artist}" />
    <TextBlock Text="{Binding Title}" />
  </StackPanel>
</DataTemplate>

...

<ListBox 
  Grid.Column="1" 
  HorizontalAlignment="Stretch" 
  VerticalAlignment="Stretch" />

I have two questions:

  1. How do I make the StackPanel fill the entire width of the ListBox? Right now, it only takes enough space to accomodate the DockPanel and the TextBlocks inside. It won't fit the width of the ListBox or ListBoxItem.
  2. Next, how do I make the DockPanel fill the entire width of the StackPanel, i.e. its parent? What happens right now is that even if the width of the TextBlocks in the StackPanel exceed the width of the DockPanel, it won't stretch to match their width.

Thanks for the help.

like image 585
Boris Avatar asked Feb 22 '11 14:02

Boris


People also ask

What is the difference between StackPanel and DockPanel?

StackPanel vs. For example, the order of child elements can affect their size in a DockPanel but not in a StackPanel. This is because StackPanel measures in the direction of stacking at PositiveInfinity, whereas DockPanel measures only the available size. The following example demonstrates this key difference.

What is DockPanel in WPF?

DockPanel defines an area to arrange child elements relative to each other, either horizontally or vertically. With DockPanel you can easily dock child elements to top, bottom, right, left and center using the Dock property.


1 Answers

You can make the Content of every ListBoxItem stretch by setting HorizontalContentAlignment in the ItemContainerStyle

<ListBox ...>
    <ListBox.ItemContainerStyle>
        <Style TargetType="ListBoxItem">
            <Setter Property="HorizontalContentAlignment" Value="Stretch"/>
        </Style>
    </ListBox.ItemContainerStyle>
like image 77
Fredrik Hedblad Avatar answered Oct 04 '22 14:10

Fredrik Hedblad