Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binding Image Dynamically in Metro App

I have an ImageSource inside ImageBrush which would be changed dynamically depends on my data.

The problem is, I can't directly access the Name of the ImageBrush because it's inside DataTemplate. I know this is bad idea, because storing data inside UI is such a bad habit.

If anyone know how to solve this using data binding on Image, i would really appreciate that. Thanks!!

<DataTemplate>
  <StackPanel Width="250" Height="180" VerticalAlignment="Bottom">
    <StackPanel.Background>
       <ImageBrush ImageSource="{Binding ???}"/>
    </StackPanel.Background>
    ........
  </StackPanel>
</DataTemplate>
like image 956
Chairil Azmi Saragih Avatar asked Nov 03 '22 09:11

Chairil Azmi Saragih


1 Answers

You can create a converter that converts the path to an image:

public sealed class ImageConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        try
        {
            return new BitmapImage(new Uri((string)value));
        }
        catch 
        {
            return new BitmapImage();
        }
    }

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

and then in the XAML:

< Image Source="{Binding Path=ImagePath, Converter={StaticResource ImageConverter}}" />
like image 149
Z.D. Avatar answered Nov 08 '22 11:11

Z.D.