Search code examples
c#silverlightwindows-phonewindows-phone-8longlistselector

Grouped LongListSelector: headers appear, items don't


WinPhone 8 project in C#. I'm trying to populate a grouped list. The group headers appear, the items don't. The relevant code is:

class MyPage
{
    public class Group : IGrouping<string, string>
    {
        public string Title{get;set;}
        public string[] Items;

        public string Key
        {
            get { return Title; }
        }

        public IEnumerator<string> GetEnumerator()
        {
            return (Items as IEnumerable<string>).GetEnumerator();
        }

        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return Items.GetEnumerator();
        }
    }

    private Group[] m_ItemGroups =
        {
            new Group(){Title = "A", Items = new string[] {"A", "ASA"}},
            new Group(){Title = "X", Items = new string[] {"X", "XX"}},
        };

    private void OnLoaded(object sender, RoutedEventArgs e)
    {
        TheList.ItemsSource = m_ItemGroups;
    }
}

And the XAML:

<phone:LongListSelector
        x:Name="TheList"
        Grid.Row="1"
        IsGroupingEnabled="True"
        SelectionChanged="OnSelChanged"
        >

        <phone:LongListSelector.GroupHeaderTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding Title}"
                   Style="{StaticResource PhoneTextGroupHeaderStyle}"
                   Foreground="{StaticResource PhoneForegroundBrush}" />
            </DataTemplate>
        </phone:LongListSelector.GroupHeaderTemplate>

        <phone:LongListSelector.ItemTemplate>
            <DataTemplate>
                <StackPanel Margin="0,0,0,17" Width="432" Orientation="Horizontal">
                    <TextBlock Text="Hello world" TextWrapping="Wrap" Width="345"/>
                </StackPanel>

            </DataTemplate>
        </phone:LongListSelector.ItemTemplate>

    </phone:LongListSelector>

Neither of the GetEnumerator() methods is called. The Key getter is never called, either. Looks like the list does not recognize my Group class as a collection of strings that it is. Please, what's wrong here?

The item template is fine. When I change the list to non-grouped, I see two items with dummy text.

Replacing the string as the item type with a custom class does not help.


Solution

  • Looks like LongListSelector expects, in grouped mode, that the objects in the ItemsSource collection implement System.Collections.IList (untyped). A simple IEnumerator won't do.

    I wish that was documented. So far, WP8 SDK docs suck big time.