I have a Silverlight application in which I'm not using XAML. I have a basic application with the following code in Application_Startup:
p开发者_开发百科rivate void Application_Startup(object sender, StartupEventArgs e)
{
Grid g = new Grid();
g.Children.Add(new Image { Source = new System.Windows.Media.Imaging.BitmapImage(new Uri("http://sstatic.net/so/img/sprites.png", UriKind.Absolute)) });
this.RootVisual = g;
}
This code will not render the specified image. If however, the App.Xaml file is modified to define the RootVisual in the Xaml the following works:
xaml:
<Application.RootVisual>
<Grid>
</Grid>
</Application.RootVisual>
code:
private void Application_Startup(object sender, StartupEventArgs e)
{
((Grid)this.RootVisual).Children.Add(new Image { Source = new System.Windows.Media.Imaging.BitmapImage(new Uri("http://sstatic.net/so/img/sprites.png", UriKind.Absolute)) });
}
I don't see why one would work and the other not. I have the same behavior using a UserControl as well (using Content instead of Childern of course).
From what I understand, there should be not XAML requirement. Is there something I'm missing?
The difference is in the first case you are setting the RootVisual
to be a Grid
, but in the second your grid is a child element.
On the MSDN page for the RootVisual property it shows the following example:
this.RootVisual = new Page();
so if you create a Page
and then add your Grid
to that page it should work.
Page page = new Page();
page.Content = g;
this.RootVisual = page;
精彩评论