3

我正在尝试用 C# 编写一个 Windows 8 应用程序,我想在其中显示用户通过 FileOpenPicker 选择的图像列表。我希望使用 XAML 数据绑定在 GridView 中显示这些图像。我已经尝试了一些东西,但数据绑定似乎不起作用。我不确定我需要在什么位置设置 GridView 的 itemssource。如果我在 MainPage 构造函数中执行此操作,则 GridView 不会刷新,因为数据绑定列表稍后会在用户选择图像时被填充。

我该如何解决?

4

1 回答 1

1

更新 1

如果你想绑定GridView,那么你需要添加一些东西。请参阅我已经用一些评论行更新了我的答案。您需要ItemsSource通过 XAML添加这些行以提供


干得好。

C#

private async void btnBrowsePhotos_Click(object sender, RoutedEventArgs e)
{
    //var objImageItem = new ImageItem();   
    FileOpenPicker openPicker = new FileOpenPicker();

    openPicker.ViewMode = PickerViewMode.Thumbnail;
    openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
    openPicker.FileTypeFilter.Add(".jpg");
    openPicker.FileTypeFilter.Add(".jpeg");
    openPicker.FileTypeFilter.Add(".png");

    var files = await openPicker.PickMultipleFilesAsync();
    List<ImageItem> ImageList = new List<ImageItem>();
    foreach (var file in files)
    {
        using (var stream = await file.OpenAsync(FileAccessMode.Read))
        {
            //objImageItem.ImageList.Add(new ImageItem(stream, file.Name));
            ImageList.Add(new ImageItem(stream, file.Name)); 
        }
    }

    gv.ItemsSource = ImageList;
    //gv.DataContext = objImageItem;
}

public class ImageItem //: INotifyPropertyChanged 
{
    /*private ObservableCollection<ImageItem> _ImageList = new ObservableCollection<ImageItem>();
    public ObservableCollection<ImageItem> ImageList
    {
         get { return _ImageList; }
         set { _ImageList = value; OnPropertyChanged("ImageList"); }
    }*/

    public BitmapImage Source { get; set; }
    public string Name { get; set; }

    public ImageItem()
    {

    }

    public ImageItem(IRandomAccessStream stream, string name)
    {
        BitmapImage bmp = new BitmapImage();
        bmp.SetSource(stream);
        Source = bmp;
        Name = name;
    }
}

XAML

<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
    <StackPanel>
        <Button Click="btnBrowsePhotos_Click" Style="{StaticResource BrowsePhotosAppBarButtonStyle}" />

        <!-- Add ItemsSource="{Binding ImageList}" to GridView -->

        <GridView x:Name="gv">
            <GridView.ItemTemplate>
                <DataTemplate>
                    <Grid>
                        <Image Stretch="Fill" Source="{Binding Source}" Height="192" Width="342" />
                        <Border Opacity=".8" Background="Black" VerticalAlignment="Bottom" >
                            <TextBlock Text="{Binding Name}" FontSize="18"/>
                        </Border>
                    </Grid>
                </DataTemplate>
            </GridView.ItemTemplate>
            <GridView.ItemsPanel>
                <ItemsPanelTemplate>
                    <WrapGrid MaximumRowsOrColumns="3" />
                </ItemsPanelTemplate>
            </GridView.ItemsPanel>
        </GridView>
    </StackPanel>
</Grid>
于 2013-06-12T06:31:11.037 回答