"Object reference not set to an instance of an object" when using SharePoint's ClientContext.Current in Silverlight

SharePoint 2010 and Silverlight is a fantastic combination, especially when you use the Client Object Model for Silverlight to access SharePoint data. But maybe you’ve encountered the following situation: your Silverlight application works great when it’s hosted in the out-of-the-box Silverlight Web Part, but when you build your own custom Web Part to show the Silverlight Application it just doesn’t work anymore: the browser tells you there is an Error on page. The details of the error are: Unhandled Error in Silverlight Application Object reference not set to an instance of an object.

When you debug your Silverlight code, you’ll notice that the issue is that the ClientContext.Current is a Null Reference. To solution for this problem is that fact that if you want to use the Current ClientContext you need to add the MS.SP.url parameter to the initParams in the HTML object that loads the XAP. This MS.SP.url parameter needs to contain the URL of the site in which the Silverlight Application is currently being displayed. The code of your Silverlight Web Part could look as follows: