Share via


How to: Size a ListBoxItem to Fill the ListBox

Controls size differently inside containers. For example, a Button inside a StackPanel sizes to the entire width of the StackPanel but a Button inside a ListBox sizes to the content of the Button. If you want Button controls inside a ListBox to stretch to fill the available space you need to create a style to stretch the ListBoxItem and apply the style to the ItemContainerStyle of the ListBox. Following is a sample that demonstrates how to do this.

Example

Style style = new Style(typeof(ListBoxItem));
style.Setters.Add(new Setter(ListBoxItem.HorizontalContentAlignmentProperty,
     HorizontalAlignment.Stretch));
ListBox lb = new ListBox();
lb.ItemContainerStyle = style;
ListBoxItem lbi1 = new ListBoxItem();
Button btn = new Button();
btn.Content = "Button as styled list box item.";
lbi1.Content = (btn);
lb.Items.Add(lbi1);
Dim style As Style = New Style()
style.Setters.Add(New Setter(ListBoxItem.HorizontalContentAlignmentProperty, _
     HorizontalAlignment.Stretch))
Dim lb As ListBox = New ListBox()
lb.ItemContainerStyle = style
Dim lbi1 As ListBoxItem = New ListBoxItem()
Dim btn As Button = New Button()
btn.Content = "Button as styled list box item."
lbi1.Content = (btn)
lb.Items.Add(lbi1)

For the complete sample see.ListBoxItem Style Sample.