Saturday, September 18, 2010

[Silverlight] Binding to list box elements throwing MethodAccessException

I spent an hour or two figuring this out, so I figured I'd post about it. Hopefully, the next poor soul who runs into it will find it here:

I was running into a problem binding my list to a Silverlight list box. On listbox creation, the output window had lots of lines that looked like this:

System.Windows.Data Error: Cannot get 'DisplayName' value (type 'System.String') from 'Magecrawl.Items.Consumable' (type 'Magecrawl.Items.Consumable'). BindingExpression: Path='DisplayName' DataItem='Magecrawl.Items.Consumable' (HashCode=45492604); 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 'Magecrawl.Items.Consumable.get_DisplayName()' failed.
   at System.RuntimeMethodHandle.PerformSecurityCheck(Object obj, RuntimeMethodHandleInternal method, RuntimeType parent, UInt32 invocationFlags)
   at System.RuntimeMethodHandle.PerformSecurityCheck(Object obj, IRuntimeMethodInfo method, RuntimeType parent, UInt32 invocationFlags)

The answer is that under Silverlight, you can not bind to non-public objects. The Consumable objects noted above was a internal object with a public interface. Once I made it public, the problem went away.

A side note, this apparently also occurs if you bind to an anonymous type as well.

No comments: