[英]How to bind xml image in listbox in windows phone 8
如何在Windows Phone 8中绑定XML图像? 我已经完成了所有方法,但是没有用,每当我调试应用程序时,它都包含Image的源,但是image不会显示。
码:
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代码:
<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>
我认为您可以尝试使用Converter(如果您在Internet上搜索Binding和Converter,会发现很多链接,教程等)。 一个简单的代码可能看起来像这样(我没有尝试过):
在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"/>
在.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 }
}
您还可以在MSDN上阅读有关绑定和转换器的更多信息。
这是我的.cs文件:
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);
和XAML文件:
<Image Source="{Binding Icon}" Stretch="Uniform" HorizontalAlignment="Center" Height="50" Width="50" VerticalAlignment="Top"/>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.