Windows Phone: Value does not fall within expected range

Value does not fall within expected range” is one of those strange errors you could run into when developing a Windows Phone 8 application, that can mean anything.

In this case, the error was being thrown when a UIElement that was already part of the visual tree was being added again to the visual tree. One of the XAML views had this line of code:

<ContentControl Name="MapContentControl" Content="{Binding MainMapView, Mode=OneTime}">

The ViewModel serving as DataContext for this view, exposed a property called MainMapView as follows:

public object MainMapView
   get { return MapViewController.CreateMainMapView().GetMapObject(); }

Thing is the MapViewController’s CreateMainMapView creates and caches an instance of a view which derives from UIElement.  When the page containing this map view is unloaded, it does not appear as though our MapView is removed from the Visual Tree, since reloading the page causes the aforementioned exception.  Changing MapViewController’CreateMainMapView to return a new instance each time is one way to solve the problem.

Another way is to simply set Content of MapContentControl to null when view unloads.  I chose the former strategy but it required a little bit of re-architecture on how map loads layers.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s