Need help with changing XAML image source in code behind

Anonymous
2021-12-07T17:04:01.443+00:00

Struggling to change an XAML image source in code behind. What I have is a ComboBox that has no items at startup. After pulling several items from a database that will be used to dictate what image is shown in the XAML image control, I add them to the ComboBox. After the items from the database are added, I then want to change the source of the image control in code from the ComboBox SelectionChanged event function. So far, this all works. What I can't seem to figure out is how to get the image source changed to the file I want shown.

Here is the code I believe is correct.

            Image img = sender.as<Image>();
            winrt::Windows::UI::Xaml::Media::Imaging::BitmapImage bitmapImage = winrt::Windows::UI::Xaml::Media::Imaging::BitmapImage();

            bitmapImage.UriSource() = Uri(img.BaseUri(), "/Image/Image.jpg");
            img.Source() = bitmapImage;

I have two problems with this, img.Source() does not really point to the XAML control. That would actually be ModelImage().Source(). This is from the XAML code.
And IntelliSense has a problem with Uri() that I can't figure out. So, maybe this is not the code I need.

Just another note, this is C++ WinRT UWP.

Developer technologies Universal Windows Platform (UWP)
Developer technologies C++
{count} votes

Accepted answer
  1. Castorix31 90,521 Reputation points
    2021-12-08T17:20:22.36+00:00

    This test based on MSDN doc works for me,
    with an Image image1 and a Butterfly.png file added in Assets :

     BitmapImage bitmapImage;
     image1().Width(320);
     bitmapImage.DecodePixelWidth(320);
     bitmapImage.UriSource(Windows::Foundation::Uri{ L"ms-appx:///Assets/Butterfly.png" });
     image1().Source(bitmapImage);
    

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.