I am trying to write a Windows 8 app in C# in which I want to display a list of images that the user selects through FileOpenPicker. I wish to display these images in a GridView using XAML Data-binding. I have tried a few things but the data-binding doesn't seem to work. I am not sure at what location exactly do I need to set the itemssource of the GridView. If I do it in the MainPage constructor then the GridView doesn't get refreshed as the data-bound list gets populated later as the user selects the images.
How do I fix this?
UPDATE 1
If you want to bind GridView
, then you need to add few things. See I have updated my answer with some comment lines. You need to add those lines to supply ItemsSource
via XAML
Here you go.
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>