Search code examples
c#wpflayoutlistboxdatatemplate

Best way to stretch WPF ListBox.ItemTemplate's contents to the width of ListBoxItem


I know this may be duplicate, but I haven't found a best solution. I simply come across a issue of using ListBox.ItemTemplate, I want the content Grid to HorizontalAlignment="Stretch"(not work). So I tried to bind the Grid' Width to the ListBoxItem, but the last item behaves strangely. If bind to the Width of ListBox, there will be a scrollbar, although a converter may solve it, I think there must be some more simple and elegant solution.

Codebehind:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        this.DataContext = new List<Data>()
        {
            new Data("a1","a2"),
            new Data("b1","b2"),
            new Data("c1","c2")
        };
    }
        public class Data
        {
            public Data(string s1, string s2)
            {
                this.S1 = s1;
                this.S2 = s2;
            }
            public string S1 { get; set; }
            public string S2 { get; set; }
        }
    }

Xaml:

<Grid>
    <ListBox ItemsSource="{Binding}">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <Grid Background="Blue" 
                      Width="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListBox}}, 
                    Path=ActualWidth, Mode=OneWay}"
                      >
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition/>
                        <ColumnDefinition/>
                    </Grid.ColumnDefinitions>
                    <TextBlock Text="{Binding S1, Mode=OneWay}" 
                               FontSize="20" Grid.Column="0"/>
                    <TextBlock Text="{Binding S2, Mode=OneWay}" 
                               FontSize="20" Grid.Column="1"/>
                </Grid>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
</Grid>

enter image description here enter image description here enter image description here


Solution

  • Try to set ListBoxItem's HorizontalContentAlignment to Strecth, for example :

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