0

I have a ListBox on my WP 8.1 Silverlight app that looks like this:

<StackPanel Grid.Column="1" Grid.Row="0" HorizontalAlignment="Center" VerticalAlignment="Top">                
    <ListBox x:Name="FavoriteListBox" Visibility="Collapsed" 
             SelectionChanged="FavoriteListBox_SelectionChanged"
             HorizontalAlignment="Stretch"
             VerticalAlignment="Top" Opacity="1"
             Background="{StaticResource PhoneBackgroundBrush}" Foreground="{StaticResource PhoneForegroundBrush}"
             Height="300" Width="250">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <TextBlock Visibility="Visible" x:Name="FavoriteListBoxTextBlock"  
                       FontSize="35" Foreground="Black" Text="{Binding AnswerName}"/>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
</StackPanel>

In my ListBox the items should look like this:

  1. item1
  2. item2
  3. to 15.....

However currently it is not in the order of 1,2,3,4... Instead it is in order of when the item is added.

I want the ListBox items to serialize automatically. How can this be achieved?

Bugs
  • 4,491
  • 9
  • 32
  • 41
Shubham Sahu
  • 1,963
  • 1
  • 17
  • 34

1 Answers1

2

If you want to sort a list or array before serializing, you can use two different solutions.

Arrays have a static Array.Sort method, that sorts the items of the array in-place (sorts the contents of the instance itself).

For lists and other collections you can use LINQ's OrderBy extension method.

var sortedList = list.OrderBy( 
    item => item.PropertyToOrderBy )
    .ToList();

Note, that the original list is left intact, the result of the ToList() extension method is a new instance.

Martin Zikmund
  • 38,440
  • 7
  • 70
  • 91