UWP C# Replacing image.

VoyTec 671 Reputation points
2022-11-04T23:31:34.327+00:00

How can I in C# replace an existing image from xaml?

Universal Windows Platform (UWP)
{count} votes

Accepted answer
  1. Roy Li - MSFT 29,346 Reputation points Microsoft Vendor
    2022-11-07T02:10:42.48+00:00

    Hello,

    Welcome to Microsoft Q&A!

    How can I in C# replace an existing image from xaml?

    If you have an existing image in Xaml like this:

       <Image x:Name="_displayImage" Source="Assets/london.png" Width="200" Height="200"/>  
    

    You could just replace the source of the Image in code behind like:

          //create a new bitmage image  
        BitmapImage bitmapImage = new BitmapImage();  
        bitmapImage.UriSource = new Uri("ms-appx:///Assets/paris.png");  
        _displayImage.Source =  bitmapImage;  
    

    If you are using binding to show the image like:

     <Image x:Name="_displayImage" Source="{Binding SourceImage,Mode=TwoWay}" Width="200" Height="200"/>  
    

    Then you could change the SourceImage in the code behind like:

              //create a new bitmage image  
            BitmapImage bitmapImage = new BitmapImage();  
            bitmapImage.UriSource = new Uri("ms-appx:///Assets/paris.png");  
            //set the new value to the binding source  
            SourceImage=bitmapImage;  
    

    Thank you.


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. 2022-11-07T03:46:25.453+00:00

    create a new bitmage image
    BitmapImage bitmapImage = new BitmapImage();
    bitmapImage.UriSource = new Uri("ms-appx:///Assets/paris.png");
    //set the new value to the binding source
    SourceImage=bitmapImage;

    1 person found this answer helpful.
    0 comments No comments