Silverlight Accordion Doesn't Like Anonymous Types

To setup an example, suppose this was an accordion being bound data to:

<mcl:Accordion x:Name="BoundAccordion">
    <mcl:Accordion.HeaderTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Title}" />   
        </DataTemplate>
    </mcl:Accordion.HeaderTemplate>
    <mcl:Accordion.ContentTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Text}" />                   
        </DataTemplate>
    </mcl:Accordion.ContentTemplate>
</mcl:Accordion>

Not the most practical example, but simple for this demonstration purposes.  I was trying to bind data to it in this format:

var list = new[]
{
   new { Title = "Title", Text = "Text" },
   .
   .
};

So the anonymous collection contained anonymous classes with Title and Text properties.  Binding this to the accordion through:

BoundAccordion.ItemsSource = list;

Raised an exception.  This is the proper way to bind the accordion because ItemsSource is inherited from the ItemsControl line of base classes.  And so ItemsSource tries to use our anonymous list, and an exception is thrown:

Sys.InvalidOperationException: Managed Runtime Error #4004
System.MethodAccessException: AnonymousType.get_Title() at MethodBase.PerformSecurityCheck

The reason, that I found out from another source, is described later...  An exception is thrown when trying to bind against the anonymous type; switching it up to bind against this works instead:

var list = new HeaderedInformationCollection
{
    new HeaderedInformation { Title = "First Bound Header", Text = "First Bound Content" },
    new HeaderedInformation { Title = "Second Bound Header", Text = "Second Bound Content" },
    new HeaderedInformation { Title = "Third Bound Header", Text = "Third Bound Content" },
    new HeaderedInformation { Title = "Fourth Bound Header", Text = "Fourth Bound Content" }
};

this.BoundAccordion.ItemsSource = list;

This result binds correctly, because the HeaderedInformation is a structured class, and not one developed on the fly.  The exception comes from the internal plumbing of the Silverlight framework, not from the Accordion control directly.  Anonymous types are internal, and Silverlight doesn't support reflecting against internal types.  While that binding setup would work in ASP.NET, it does not in Silverlight.  Bummer.

Comments

No Comments