Freitag, 27. April 2012

Silverlight DataBinding und NULL

I recently noticed that, if you have an ObservableCollection<Something> in Silverlight bound to an ItemsControl with an explicit DataTemplate attached to it, that if you insert a NULL reference in to the collection you get the following error message:


Zeile: 1587
Fehler: Unhandled Error in Silverlight Application
Code: 4004   
Category: ManagedRuntimeError      
Message: System.Collections.Generic.KeyNotFoundException: Der angegebene Schlüssel war nicht im Wörterbuch angegeben.
   at System.Collections.Generic.Dictionary`2.get_Item(TKey key)
   at System.Windows.ResourceManagerWrapper.GetResourceForUri(Uri xamlUri, Type componentType)
    



While this seems cryptic in the first place, it still makes perfectly sense: for the type of object you add there is no something in the resource dictionaries to display it - hence the error.

The ugly thing is, that the error causes Silverlight to crash completely. A registered ApplicationUnhandledException handler just setting e.Handled = true does not seem to help either. So if you add something to a bound collection always check for null.

Maybe this saves some of you some time...

Cheers,
Tobias.

Keine Kommentare:

Kommentar veröffentlichen