Vincent
Vincent

Reputation: 3304

XAML set image property to values using DependencyProperty

I have a model like:

{
    "images": [{
        "image_url": "..........",
        "orientation": "horizontal"
    },
    {
        "image_url": "...............",
        "orientation": "vertical"
    }]
}

and a ListView DataTemplate

<DataTemplate x:DataType="model:ImageItem">
    <controls:ImageEx Source="{x:Bind cover_image_url}" PlaceholderSource="" PlaceholderStretch="Uniform"/>
</DataTemplate>

Now, I want the ImageEx control's PlaceholderSource property change along with orientation.

More clearly, when the image property is horizontal, ImageEx will load a place holder 1. When the image property is vertical, ImageEx will load a place holder 2.

How to do this. Please show me.

Upvotes: 0

Views: 57

Answers (1)

Nico Zhu
Nico Zhu

Reputation: 32785

More clearly, when the image property is horizontal, ImageEx will load a place holder 1. When the image property is vertical, ImageEx will load a place holder 2.

You could use IValueConverter interface to approach, use converter class to converter different message type to different PlaceholderSource for ImageEx. You could refer the follow ImageConverter.

public class ImageConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, string language)
    {
        object img = null;

        switch (value.ToString())
        {
            case "horizontal":
                img = new BitmapImage(new Uri("ms-appx:///Assets/holder1.png"));
                break;
            case "vertical":
                img = new BitmapImage(new Uri("ms-appx:///Assets/holder2.png"));
                break;
            default:
                break;
        }

        return img;
    }

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

Xaml

<Page.Resources>
        <local:ImageConverter  x:Key="Converter"/>
</Page.Resources>

       ......

<DataTemplate x:DataType="model:ImageItem">
    <controls:ImageEx Source="{x:Bind cover_image_url}" PlaceholderSource="{x:Bind orientation,Converter={StaticResource Converter}}" PlaceholderStretch="Uniform"/>
</DataTemplate>

Upvotes: 1

Related Questions