Search code examples
c#wpfxamllistboxstackpanel

Visual C#: Can't find correct relative width for listbox


So I have a listbox and I'm trying to use a stackpanel inside as an item with a border. Now I want every item to be the same width as my listbox, which is anchored to the sides of the window. I found how to set the width relative to the parent but for some reason it turns out to be wider. Can't seem to figure out why. Picture below code of how it looks.

<ListBox x:Name="listBoxSecrets" Margin="10,107,10,10" Background="{x:Null}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <Border BorderBrush="Orange" CornerRadius="2,2,2,2" BorderThickness="2,2,2,2">
                <StackPanel Background="White" 
                            Width="{Binding RelativeSource=
        {RelativeSource FindAncestor,
        AncestorType={x:Type ListBox}},
        Path=ActualWidth}"
                            >
                    <TextBlock Text="{Binding Path=Name}" />
                    <TextBlock Text="{Binding Path=Totp}" />
                </StackPanel>
            </Border>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

enter image description here


Solution

  • ListBox.ActualWidth is too much for ListBoxItems. But ListBoxItems will use all available width if ListBox has HorizontalContentAlignment set to "Stretch":

    <ListBox HorizontalContentAlignment="Stretch"