Need some help in ListBox DataBindg in Silverlight for Windows Phone. The code as follows:
1) On Page Load Event :
Note : Pictures is a collection of picture, PicNames is collection of names of pictures.
var ml = new MediaLibrary();
var ChkPics = ml.Pictures;
var PicNames = from p in ChkPics
where p.Name.Contains("s")
select p;
2) Static Class
public static class PhotoNames
{
private static List<string> m_Photoname = new List<string>();
public static List<string> PhotoFileNames
{
get
{
return m_Photoname;
}
set
{
m_Photoname = value;
}
}
}
After getting all the photo filenames in the PicNames in this way:
On Page Load Event :
var ml = new MediaLibra开发者_C百科ry();
var ChkPics = ml.Pictures;
var PicNames = from p in ChkPics
where p.Name.Contains("s")
select p;
foreach (var pic in PicNames)
{
PhotoNames.PhotoFileNames.Add(pic.Name);
}
How do I bind a ListBox to this static class and show all the data in TextBlock
inside ListBox?
Thanks.
It looks like ml.Pictures has all the info you need (name and picture). Why do you need the static class?
You could do the following:
var ml = new MediaLibrary();
listBox.ItemSource = ml.Pictures.Where(picture => picture.Name.Contains("s"));
And in your XAML:
<UserControl.Resources>
<local:ImageConverter x:Key="ImageConverter"></local:ImageConverter>
...
</UserControl.Resources>
<ListBox x:Name="listBox">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="120"></ColumnDefinition>
<ColumnDefinition Width="35"></ColumnDefinition>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"></RowDefinition>
</Grid.RowDefinitions>
<TextBlock Grid.Column="0" Grid.Row="0" Text="{Binding Name}"></TextBlock>
<Image Grid.Column="1" Grid.Row="0" Source="{Binding Picture, Converter={StaticResource ImageConverter}}"></Image>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
The template shows both the picture's name and the picture itself in a thumbnail, if you don't need the picture, use DisplayMemberPath instead.
<ListBox x:Name="listBox" DisplayMemberpath="Name">
</ListBox>
/// <summary>
/// Converts an image path to the associated image.
/// </summary>
public class ImageConverter : IValueConverter
{
#region IValueConverter implementation
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
string imagePath = (string)value;
Uri Uri = new Uri(imagePath, UriKind.Relative);
return new BitmapImage(Uri);
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
精彩评论