How to bind xml image in windows phone 8? I have done all methods but its not working, Whenever I debug the application, it contains source of an Image but, image is not displaying.
Code:
List<LIST> lst = new List<LIST>();
lst = (from query in doc.Descendants("row") select new LIST
{ Id = Convert.ToInt64(query.Element("Id").Value),
Icon = query.Element("Icon").Value,
xyz = Convert.ToInt64(query.Element("xyz").Value),
Url = query.Element("Url").Value, Name = query.Element("Name").Value }).ToList();
listBox1.DataContext = lst;
XAML Code:
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Image Source="{Binding Icon}" Stretch="Uniform" HorizontalAlignment="Center" Height="50" Width="50" VerticalAlignment="Top"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
I think you can try to use a Converter (if you search internet for Binding and Converter, you will find many links, tutorials etc.). A simple code can look like this (I haven't tried it):
In XAML:
...
xmlns:common="clr-namespace:YourNamespace"
...
<phone:PhoneApplicationPage.Resources>
<common:ToImageSource x:Key="converter"/>
</phone:PhoneApplicationPage.Resources>
...
<Image Source="{Binding Icon, Converter={StaticResource converter} }" Stretch="Uniform" HorizontalAlignment="Center" Height="50" Width="50" VerticalAlignment="Top"/>
In .cs:
public class ToImageSource : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value == null) return null;
else
{
byte[] imageBytes = Convert.FromBase64String(value);
using (MemoryStream stream = new MemoryStream(imageBytes, 0, imageBytes.Length))
{
stream.Write(imageBytes, 0, imageBytes.Length);
BitmapImage bitmap = new BitmapImage();
bitmap.SetSource(stream);
return bitmap;
}
}
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{ // implement ConvertBack }
}
You can also read more about binding and converters at MSDN .
Here is my .cs file:
public static BitmapImage getImage(string img)
{
byte[] filebytes = Convert.FromBase64String(img);
MemoryStream ms = new MemoryStream(filebytes, 0, filebytes.Length);
BitmapImage image = new BitmapImage();
image.SetSource(ms);
return image;
}
Icon = getImage(query.Element("Icon").Value);
and XAML file:
<Image Source="{Binding Icon}" Stretch="Uniform" HorizontalAlignment="Center" Height="50" Width="50" VerticalAlignment="Top"/>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.