C # windows phone - Run in xaml ListBox.ItemTemplate

I would like to make a simple ListBox. Each line should contain 2 controls, one to the left, the other to the right, that's all :) I tried several approaches, but nothing worked. My code is as follows

<StackPanel Grid.Row="1" Margin="12,0,12,0" Grid.Column="0"> <ListBox Name="ListBox" Margin="12,0,12,0" ItemsSource="Exercises" HorizontalContentAlignment="Stretch"> <ListBox.ItemTemplate> <DataTemplate> <StackPanel Orientation="Horizontal" Width="> <TextBlock Text="abc" HorizontalAlignment="Left" VerticalAlignment="Center"/> <TextBlock Text="def" HorizontalAlignment="Right" VerticalAlignment="Center"/> </StackPanel> </DataTemplate> </ListBox.ItemTemplate> </ListBox> </StackPanel> 

(Two text blocks are for demonstration purposes only, in a real application, I would like to bind one text block to real data, instead of the second bad use button.) When this is poorly compiled, both text blocks are left-aligned, in the emulator, it looks like one text block with the text "abcdef". Any idea how to align one text block to the right and the other to the left? thank you very much:)

+5
source share
1 answer

By default, a ListBoxItem does not fill in the space that it sets. He aligns himself and the contents on the left. For the contents of your ListBoxItem to span the entire width, you need to change the ItemContainerStyle

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

Now the content will cover the available width. If you want to use the StackPanel, as in your example, be sure to set HorizontalAlignment. StackPanel also does not fill the available space indicated by

 <DataTemplate> <StackPanel Orientation="Horizontal" HorizontalAlignment="Stretch"> <TextBlock Text="abc" HorizontalAlignment="Left" VerticalAlignment="Center"/> <TextBlock Text="def" HorizontalAlignment="Right" VerticalAlignment="Center"/> </StackPanel> </DataTemplate> 

However, I would recommend using a Grid and defining two columns

 <DataTemplate> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="*" /> <ColumnDefinition Width="*" /> </Grid.ColumnDefinitions> <TextBlock Text="abc" HorizontalAlignment="Left" VerticalAlignment="Center"/> <TextBlock Text="def" Grid.Column="1" HorizontalAlignment="Right" VerticalAlignment="Center"/> </Grid> </DataTemplate> 
+16
source

All Articles