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:
- How do I make the
StackPanelfill the entire width of theListBox? Right now, it only takes enough space to accomodate theDockPaneland theTextBlocks inside. It won’t fit the width of theListBoxorListBoxItem. - Next, how do I make the
DockPanelfill the entire width of theStackPanel, i.e. its parent? What happens right now is that even if the width of theTextBlocks in theStackPanelexceed the width of theDockPanel, it won’t stretch to match their width.
Thanks for the help.
You can make the Content of every
ListBoxItemstretch by settingHorizontalContentAlignmentin the ItemContainerStyle