How to make DockPanel fill available space
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>
The nice thing about dock panels is they already fill all the available space. LastChildFill is true by default (but I set it below for clarity), so just don't set the DockPanel attribute on the last child, and it will fill the available space.
<DockPanel HorizontalAlignment="Stretch" LastChildFill="true"> <TextBlock DockPanel.Dock="Left" Text="{Binding Path=Name}" FontSize="10" Foreground="Black" /> <TextBlock Text="{Binding Path=Price, StringFormat=\{0:C\}}" FontSize="10" Foreground="Black" /></DockPanel>
DockPanel
s are evil. Temptation to use StackPanel/DockPanel
combination for complex layouts leads to "layout dead ends". Use a Grid:
<Grid> <TextBlock HorizontalAlignment="Left"... <TextBlock HorizontalAlignment="Right".../Grid>
I use Grid
s almost exclusively, using a separate grid for each block of elements that "belong together"