I’m loading an image to a background, and I want the silverlight canvas containing it all to resize to the image size (or maximum or minimum that I determine) of whatever the size of the image is. So I’ve done the following:
private int ImageMargin = 4;
public Page()
{
InitializeComponent();
BitmapImage bi = new BitmapImage(new Uri("1.jpg", UriKind.Relative));
backgroundImage.Source = bi;
bi.DownloadProgress += new EventHandler<DownloadProgressEventArgs>(bi_DownloadProgress);
backgroundImage.SizeChanged += new SizeChangedEventHandler(backgroundImage_SizeChanged);
}
void bi_DownloadProgress(object sender, DownloadProgressEventArgs e)
{
if (e.Progress == 100)
{
LayoutRoot.Height = backgroundImage.Height + ImageMargin * 2;
LayoutRoot.Width = backgroundImage.Width + ImageMargin * 2;
}
}
The image loads correctly, but no matter where I seem to put the backgroundImage.Height/Width (off .Loaded event, .SizeChanged event [1], Using a border [2], etc), it always returns 0.0 or NaN. What am I doing wrong?
[1] http://silverlight.net/forums/t/14855.aspx
[2] http://silverlight.net/forums/t/90235.aspx
Ah, solution! Silverlight Tip of the Day #13 – How to Get an Images Dimensions in Silverlight.
The KEY was this line: