Sam
Sam

Reputation: 30288

Setting image source in view model in .NET MAUI app

In my .NET MAUI app, I want to be able to set my image source by binding it to a property in my view model -- see below:

public partial class MyViewModel : BaseViewModel
{
   [ObservableProperty]
   ImageSource myImageSource;

   void Init()
   {
        if(somevalue == "something")
           MyImageSource = ImageSource.FromFile("image_a.png");
        else
           MyImageSource = ImageSource.FromFile("image_b.png");
   }
}

And in my XAML page< I do this:

<Image
   Source{Binding MyImageSource}
   HeightRequest="30"
   HorizontalOptions="Center"
   VerticalOptions="Center" />

This doesn't display the image but no errors. In my view model, I also tried MyImageSource = ImageSource.FromResource("MyProject.Resources.Images.image_a.png"); which also doesn't display the image.

The images I want to display are in Resources > Images folder.

What am I doing wrong here? How do I set the image source to a file in a folder under Resources through my view model?

Upvotes: 8

Views: 15897

Answers (2)

Jessie Zhang -MSFT
Jessie Zhang -MSFT

Reputation: 13853

A method is to set your images's Build Action to Embedded resource and set value for MyImageSource in your view Model constructor,just as follows:

public partial  class MyViewModel:ObservableObject 
    {
        [ObservableProperty]
        ImageSource myImageSource;
    
        public MyViewModel()
        {
            MyImageSource = ImageSource.FromResource("YourAppName.Resources.Images.test.png", typeof(MyViewModel).GetTypeInfo().Assembly); 
        }
       
        }
    }

And bind like this:

<Image   Source="{Binding MyImageSource }" Aspect="AspectFill" WidthRequest="50"   HeightRequest="50" />

Note:

1.YourAppName is the name of the app,you can change it to yours.

2.Please change your images' Build Action to Embedded resource

Upvotes: 2

H.A.H.
H.A.H.

Reputation: 3897

In project:

<MauiImage Include="Resources\Images\*" />

File in folder:

Resources/Images/dotnet_bot.svg

Define:

[ObservableProperty]
ImageSource image;

Use:

Image = "dotnet_bot.png";

Upvotes: 9

Related Questions