[英]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.