[英]Windows Phone 8.1 ListBox ItemTemplate with a C# method for each item
目前,我在靜態頁面上使用以下代碼在頁面中加載圖像。
圖像存儲在隔離的存儲中,並且在數據庫中存儲圖像的位置。
該圖像已成功從隔離存儲中讀取,並顯示在我的靜態頁面上。
我現在想做的是在ListBox
使用相同的圖像。 但是如何通過DataTemplate
將相同的代碼過程綁定到每個ListBox
項目?
這是在我的靜態頁面上運行的代碼。
private void ReadFromIsolatedStorage(string _filename)
{
if (_filename != null)
{
WriteableBitmap bitmap = new WriteableBitmap(200, 200);
using (IsolatedStorageFile myIsoStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream fileStream = myIsoStorage.OpenFile(_filename, FileMode.Open, FileAccess.Read))
{
//StreamResourceInfo sri = Application.GetResourceStream(fileStream);
bitmap = PictureDecoder.DecodeJpeg(fileStream);
BinaryReader binary = new BinaryReader(fileStream);
byte[] imgByteArray = binary.ReadBytes((int)(fileStream.Length));
binary.Close();
binary.Dispose();
_imagearray = imgByteArray;
}
}
this.imagebox1.Source = bitmap;
//StreamResourceInfo sri = bitmap;
}
}
這是ListBox
的不完整xaml,我需要以某種方式鏈接到上面的代碼。
<ListBox Name="List1" Height="463" SelectionChanged="List1_SelectionChanged">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<Grid >
<Grid.ColumnDefinitions>
<ColumnDefinition Width="95" />
<ColumnDefinition Width="133" />
<ColumnDefinition Width="129" />
<ColumnDefinition Width="63" />
</Grid.ColumnDefinitions>
<Image Height="60" Width="60" Stretch="Uniform" Name="imageprofile" />
<TextBlock Grid.Column="1" Text="{Binding Type}" TextWrapping="Wrap"/>
<TextBlock Grid.Column="2" Text="{Binding One}" TextWrapping="Wrap"/>
<TextBlock Grid.Column="3" Text="{Binding two}" />
</Grid>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
您需要一個IValueConverter
您的頁面靜態資源:
<Page.Resources>
<converters:FilenameToBitmapImageConverter x:Key="FilenameToBitmapImageConverter"/>
</Page.Resources>
在您的項目模板中:
<Image Source="{Binding FileName,Converter={StaticResource FilenameToBitmapImageConverter}}"/>
您的轉換器代碼:
public class FilenameToBitmapImageConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
string fileName = value as string;
if (fileName != null)
{
WriteableBitmap bitmap = new WriteableBitmap(200, 200);
using (IsolatedStorageFile myIsoStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream fileStream = myIsoStorage.OpenFile(fileName, FileMode.Open, FileAccess.Read))
{
//StreamResourceInfo sri = Application.GetResourceStream(fileStream);
bitmap = PictureDecoder.DecodeJpeg(fileStream);
}
}
return bitmap;
}
return null;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.