I am trying to align the content of a ListBoxItem. In the example below I want to have the TextBlock left aligned and the Button right aligned in each row of the ListBox. But the Button always follows directly after the end of the TextBlock’s text and isn’t right aligned in the ListBox.
<StackPanel>
<ListBox ItemsSource="{Binding MyDataList}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding SomeTextProperty}"
VerticalAlignment="Center" Margin="5" />
<Button Content="Display"
HorizontalAlignment="Right" Margin="5"
Command="{Binding SomeCommand}"
CommandParameter="{Binding}"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</StackPanel>
Something needs to be changed in my XAML, I guess. What am I doing wrong?
Thanks for help!
You’ll need a different panel type, but you’ll also need to get the content to stretch across the ListBox. You can either specify it as a ControlTemplate for the ListBoxItem, or use the DataTemplate and set ListBox HorizontalContentAlignment to stretch (+1 to Dan Bryant in his comment under the question for pointing this out).
or