Arti
Arti

Reputation: 7772

Set image from code

I added image to Resources:

Right click on project -> Properties -> Resources.

Then set variable in Class:

var icon = Resources.BLUEJAYF4

In XAML use it like:

<Image Source="{Binding icon }" Width="150" Height="150"></Image>

But it doesn't show. How to set Resource path from code?

Upvotes: 1

Views: 56

Answers (1)

Kikootwo
Kikootwo

Reputation: 380

Maybe this isn't the best way to do it. But this is how I handle binding images programmatically.

You should have a property of BitmapImage like so:

    private BitmapImage photoSelected;

    public BitmapImage PhotoSelected
    {
        get { return photoSelected; }
        set { photoSelected = value; OnPropertyChanged("PhotoSelected"); }
    }

Then on the action that you desire you do this:

PhotoSelected = new BitmapImage(new Uri(@"pack://application:,,,/Images/4.png"));

Replace /Images/4.png with the path to your image starting at the solution level. For example, this is what my solution tree looks like to reach that point:

Solution Tree

Edit: I didnt think about this, but here is also the xaml I use to bind to that property.

<Image x:Name="BitMapImage" Source="{Binding PhotoSelected, Mode=TwoWay}" RenderOptions.BitmapScalingMode="HighQuality"/>

Upvotes: 1

Related Questions