Silverlight – Image Resources Fail to Display in Popup unless Application RootVisual is a UserControl (or the Popup is added to the Visual Tree!)

Whilst developing a LOB application using Silverlight and Prism we came across the bug described in the title above.

To replicate, try adding this code to a new Silverlight Application:  (of course modifying the image uri to point to a valid source)

   1: public partial class MainPage : UserControl
   2: {
   3:    public MainPage()
   4:    {
   5:       InitializeComponent();
   6:       
   7:       var i = new Image
   8:       {
   9:          Source = new BitmapImage(
  10:             new Uri(@"/ImageProblem;component/Resources/Silverlight.png", UriKind.Relative))
  11:       };
  12:  
  13:       new Popup { Child = i, IsOpen = true };
  14:  
  15:    }
  16: }

… and modify Application_Startup in app.xaml.cs to this…

   1: private void Application_Startup(object sender, StartupEventArgs e)
   2: {
   3:   Grid g = new Grid();
   4:    g.Children.Add(new MainPage());
   5:    this.RootVisual = g;
   6: }

…then run the app.  You will notice the image does not show in the popup.  If you change the RootVisual back to ‘MainPage’ (a usercontrol) and re-run the app the image will show.  Alternatively you can add the popup to the visual tree to solve the problem.  I do agree the sample code above is contrived, but the code has been reduced (from something far more sensible) to its most fundamental parts to show the problem.

Hopefully this post may save someone else the hours of effort tracking down and working around this rather unusual bug.

Comments

No comments posted yet.

Leave Your Comment

Title*
Name*
Email (never displayed)
 (will show your gravatar)
Url
Comment*

Please add 2 and 5 and type the answer here:

Preview Your Comment.