pixel
pixel

Reputation: 10577

UWP Show Image Dynamically Based on a Value of a Bindable Property

I am trying to learn how bindings and converters work and I am struggling

How do I bind an image to a ViewCell based on a binable property called Status?

For example:

I have an Image which Source is set to the Status property like below but this is not working, image is not displayed. My guess is that I need to write a converter to somehow convert the Status value to an image

<Image x:Name="StatusIcon" Source="{Binding Status}"/>

My images are locaed in the UWP project root and if I do this:

<Image x:Name="StatusIcon" Source="ms-appx:///Image1.png" />

, then my image will show properly but I need it to change dynamically based on the Status property.

Upvotes: 0

Views: 313

Answers (1)

Vijay Nirmal
Vijay Nirmal

Reputation: 5837

You are right. You need to use a converter to convert the string to corresponding Images.

Here is a sample code

public class ImageConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, string language)
    {
        switch (value as string)
        {
            case "X":
                return new BitmapImage(new Uri("ms-appx:///Image1.png"));
            case "Y":
                return new BitmapImage(new Uri("ms-appx:///Image2.png"));
            case "Z":
                return new BitmapImage(new Uri("ms-appx:///Image3.png"));
            default:
                return new BitmapImage(new Uri("ms-appx:///Default.png"));
        }
    }

    public object ConvertBack(object value, Type targetType, object parameter, string language)
    {
        throw new NotImplementedException();
    }
}

Upvotes: 1

Related Questions