Spyral Spyral - 1 year ago 107
C# Question

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}">
<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}},
<TextBlock Text="{Binding Path=Name}" />
<TextBlock Text="{Binding Path=Totp}" />

enter image description here

Answer Source

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

<ListBox HorizontalContentAlignment="Stretch" 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download