如何数据绑定Silverlight for Windows Phone7中的ListBox

时间:2010-10-11 03:53:22

标签: silverlight-4.0

在Silverlight for Windows Phone中的ListBox DataBindg中需要一些帮助。代码如下:

1)在页面加载事件:

注意:图片是图片的集合,PicNames是图片名称的集合。

var ml = new MediaLibrary();
var ChkPics = ml.Pictures;
var PicNames = from p in ChkPics
               where p.Name.Contains("s")
               select p; 

2)静态类

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;
        }
    }
}

以这种方式获取PicNames中的所有照片文件名后:

在页面加载事件:

var ml = new MediaLibrary();
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);
}

如何将ListBox绑定到此静态类并显示ListBox中TextBlock内的所有数据?

感谢。

1 个答案:

答案 0 :(得分:0)

它看起来像ml.Pictures拥有你需要的所有信息(名称和图片)。为什么需要静态类?

您可以执行以下操作:

var ml = new MediaLibrary();
listBox.ItemSource = ml.Pictures.Where(picture => picture.Name.Contains("s"));

在你的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>

模板在缩略图中显示图片的名称和图片本身,如果您不需要图片,请改用DisplayMemberPath。

<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();
    }
}