22 May
2010

Silverlight – DataBind to an Anonymous type (Who knew?)

Category:UncategorizedTag: :

I searched the web for the idea first. I was certain somebody had blogged about this before, and just wanted to quickly confirm it’s truth. Unfortunately all I came across were work-a-rounds and people telling you it’s not possible. So hopefully this post will help the next guy.

Since anonymous types are generated in an assembly as internal types, by default, if you try to DataBind to an anonymous type, you’ll probably receive a binding error much like the following.

System.Windows.Data Error:
    Cannot get 'Age' value (type 'System.Int32') from '{ Name = World, Age = 23 }' (type '<>f__AnonymousType0`2[System.String,System.Int32]').
    BindingExpression: Path='Age' DataItem='{ Name = World, Age = 23 }' (HashCode=-172495608);
    target element is 'System.Windows.Controls.TextBlock' (Name='');
    target property is 'Text' (type 'System.String')..
    System.MethodAccessException: Attempt by method 'System.Windows.CLRPropertyListener.get_Value()'
    to access method '<>f__AnonymousType0`2<System.__Canon,System.Int32>.get_Age()' failed.

   at System.RuntimeMethodHandle.PerformSecurityCheck(Object obj,...
   at System.RuntimeMethodHandle.PerformSecurityCheck(Object obj,...
   at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, Bind...
   at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, Bind...
   at System.Reflection.RuntimePropertyInfo.GetValue(Object obj, ...
   at System.Reflection.RuntimePropertyInfo.GetValue(Object obj, ...
   at System.Windows.CLRPropertyListener.get_Value()
   at System.Windows.PropertyAccessPathStep.ConnectToPropertyInSo...

Turns out, it _IS_ possible to DataBind to an anonymous type in Silverlight.

All you have to do is expose your privates. Placing the following into your AssemblyInfo.cs will give the built in bindings the ability DataBind to your object(s).

[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(“System.Windows”)]

I’m not going to say whether this is or is not a good idea, and I’m sure there’s many ways to abuse it.

Don’t inhale too much of this stuff.

One thought on “Silverlight – DataBind to an Anonymous type (Who knew?)”

  1. “All you have to do is expose your privates.”
    – Great advice for any situation!

Comments are closed.