Ganesh kudva
Ganesh kudva

Reputation: 1040

UWP WIndows-10 Loading images in app

I have a C# app targeting Windows UWP platform. App displays images in list view. Based on the query made, these images can come from either app's

  1. container(/Assets/ folder)
  2. Online source
  3. Local source


When the image's source is either in app's container or online source I can bind the Image Source to a valid URI in XAML to fetch the image.
When the image's source is local, the url for the image is proprietary & we use our own imge_fetch api to get the image from our servers.

My problem is how to specify a XAML binding which is capable of taking either a uri(when image is from app's container or online source) or BitmapImage(returned by our image_fetch apis)


I have checked this post regarding IValueConverter
I want to know, if there are any better/easier way in UWP to do what I am trying to achieve.

Upvotes: 0

Views: 1817

Answers (1)

Clemens
Clemens

Reputation: 128061

You may create a view model item class with a source property of type object, so that you can assign a string, Uri or ImageSource:

public class ImageItem
{
    public object ImageSource { get; set; }
}

In XAML, you can directly bind to this property and benefit from built-in automatic type conversion:

<ListBox ItemsSource="{Binding}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <Image Source="{Binding ImageSource}"/>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

Assigning image items my look like this:

DataContext = new ImageItem[]
{
    new ImageItem { ImageSource = "ms-appx:///Assets/StoreLogo.png" },
    new ImageItem { ImageSource = new Uri("ms-appx:///Assets/Square150x150Logo.scale-200.png") },
    new ImageItem { ImageSource = new BitmapImage(new Uri("ms-appx:///Assets/Square44x44Logo.scale-200.png")) },
};

Upvotes: 3

Related Questions