Let me explain, for different reason it is sometimes necessary to have access to the dimensions of an image in the XAML document informed of your application.
XAML:
Code:
<Image x: Name = "imPreview" Width = "200" Height = "120" Source = "image.jpg" />
Code (C #):
Code:
imPreview.GetValue (Image.WidthProperty);
But what happens when I do not wish to impose a size and a source for my image in the XAML? Stupidly ... I do not describe the properties Width and Height in my XAML document and I will then load the image source via code.
Code:
XAML:
<Image x: Name = "imPreview" />
Code:
Code (C #):
BitmapImage bi = new BitmapImage (new Uri ("image.jpg", UriKind.Relative));
imPreview.Source = bi;
And in this case the C # code (imPreview.GetValue (Image.WidthProperty)) returns NaN and it is the same for the value ActualWidth ... Thus we find ourselves stuck.
To manipulate the image at will and get the image size you will have to use a "workaround" via the event image "SizeChanged".
What gives, on page load:
Code:
BitmapImage bi = new BitmapImage (new Uri ("image.jpg", UriKind.Relative));
imPreview.Source = bi;
imPreview.SizeChanged + = new SizeChangedEventHandler (imPreview_SizeChanged);
imPreview_SizeChanged void (object sender, SizeChangedEventArgs e)
(
// E.PreviousSize.Width; Similarly Height
// E.NewSize.Width; Similarly Height
)
So you can find the size of your image using NewSize. By altering the stretch of the image you get well real size of the image in your XAML page.
Ex1: <Image x: Name = "imPreview" Stretch = "None" />
Returns the physical size of the image since it is not distorted.
Ex2: <Image x: Name = "imPreview" Stretch = "Fill" />
Returns the size of the image stretch to the parent element.
Note: If your parent is a container <canvas> you will not be able to retrieve the event SizeChanged.
While the image does not download, we can not get the size assumed. The idea is to listen to the SizeChanged image to intercept the load of the image in the XAML document. There are other possibilities such as using an interval but it is much less clean
Bookmarks