locked
Image defined in xaml does not exist in loaded event in c#

    Question

  • Hello,

    here the code of the Problem:

        <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
            <Image x:Name="img01" Source="Assets/case01Alu.gif" HorizontalAlignment="Left" Height="251" Margin="113,91,0,0" VerticalAlignment="Top" Width="407"/>
            <Button Content="Test01" x:Name="btnTest01" HorizontalAlignment="Left" Margin="113,425,0,0" VerticalAlignment="Top" Click="btnTest01_Click"/>
    ....
    

    c# code:

            void MainPage_Loaded(object sender, RoutedEventArgs e)
            {
                int w = ((BitmapSource)img01.Source).PixelWidth;
    ...

    This does not work.  PixelWidth is 0 (Zero), but real it is 550.

    in Button EventHandler:

            private void btnTest01_Click(object sender, RoutedEventArgs e)
            {
                int w = ((BitmapSource)img01.Source).PixelWidth;
    
     ....

    Here it works, pixelwidth is 550.

    BUT: I Need the pixelWidth of the Image in the loaded-Event.

    How can I do this.

    Thank you for any help.

    Rowe10

    Thursday, April 02, 2015 7:23 PM

Answers

  • Hello,

    thank you for the Information,

    BUT: there shoud be a ctrl/page loaded Event, which fires when all is rendered on the page.

    For example: I have 10 Images, then I have to get the Events of all the Images, and can get the sizes, when all have fired.

    So with Image sizechanged it works, but it's nothing for the future.

    Rowe10

    • Marked as answer by rowe10 Friday, April 17, 2015 5:03 AM
    Tuesday, April 07, 2015 9:38 PM

All replies

  • You get the image dimensions after it gets rendered on the page. And this only occurs after the page is loaded. This is why the event "img01_SizeChanged" fires before and after the "MainPage_Loaded" event.

    So you could check for the second time the img01_SizeChanged event gets fired and get the dimensions from there. Not the most effective way to get the value but you don't have to click on a button to get it.

    Hope this helps.


    Abdulwahab Suleiman




    Friday, April 03, 2015 2:29 AM
    Moderator
  • as abdulwahab was saying, the image is not yet loaded when the page gets loaded. Although the Loaded event of the image rather than the page should help in this scenario. (not even sure SizeChanged would fire when the image actually gets loaded)

    Can Bilgin(@can_bilgin)
    Blog Samples CompuSight

    Saturday, April 04, 2015 6:18 AM
  • Hello,

    thank you for the Information,

    BUT: there shoud be a ctrl/page loaded Event, which fires when all is rendered on the page.

    For example: I have 10 Images, then I have to get the Events of all the Images, and can get the sizes, when all have fired.

    So with Image sizechanged it works, but it's nothing for the future.

    Rowe10

    • Marked as answer by rowe10 Friday, April 17, 2015 5:03 AM
    Tuesday, April 07, 2015 9:38 PM