How to make DockPanel fill available space

Richard McGuire picture Richard McGuire · Jul 3, 2009 · Viewed 57.5k times · Source

I'm trying the content of a shopping cart in an ItemsControl(ListBox). To do so, I've created the following DataTemplate:

<DataTemplate x:Key="Templates.ShoppingCartProduct"
              DataType="{x:Type viewModel:ProductViewModel}">
    <DockPanel HorizontalAlignment="Stretch">
        <TextBlock DockPanel.Dock="Left"
                   Text="{Binding Path=Name}"
                   FontSize="10"
                   Foreground="Black" />
        <TextBlock DockPanel.Dock="Right"
                   Text="{Binding Path=Price, StringFormat=\{0:C\}}"
                   FontSize="10"
                   Foreground="Black" />
    </DockPanel>
</DataTemplate>

When the items are displayed in my shopping cart however, the Name and Price TextBlocks are sitting right beside one another, and there is an extremely large amount of whitespace on the right hand side.

Was wondering what the best method to force the DockPanel to stretch to fill all the space made available by the ListItem was?

Answer

Thomas Levesque picture Thomas Levesque · Jul 3, 2009

Bind the Width of the DockPanel to the ActualWidth of the ListBoxItem:

<DockPanel Width="{Binding ActualWidth, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListBoxItem}}}">
...

Another option: you could just redefine the ItemContainerStyle so that the ListBoxItem is stretched horizontally:

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