gpt4 book ai didi

c# - Windows 8 XAML : Displaying a list of images in a GridView through data binding

转载 作者:行者123 更新时间:2023-11-30 17:53:40 25 4
gpt4 key购买 nike

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

我该如何解决这个问题?

最佳答案

更新 1

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


给你。

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>

关于c# - Windows 8 XAML : Displaying a list of images in a GridView through data binding,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17056989/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com