在 C# 中导航时从列表框选定索引获取图像源
本文关键字:索引 获取 图像 列表 导航 | 更新日期: 2023-09-27 18:35:38
我有一个列表框与来自 SampleData 源的图像绑定。在选择 ListBox 项时,我想在下一页中显示图像,因此我已经在导航中传递了 SelectedIndex,但我无法获取图像或显示它。我的代码如下:'
专辑图片.cs
公共类相册图像:可观察集合 {
}
相册图片.cs
公共类相册图像 { 公共字符串标题 { get; set; }
public string content { get; set; }
}
//App.xaml.cs
private static MainViewModel viewModel = null;
public AlbumImages albumImages = new AlbumImages();
public int selectedImageIndex;
//MainPage.xaml.cs
private void listBoxPhoto_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
{
if (listBoxPhoto.SelectedIndex == -1) return;
this.NavigationService.Navigate(new Uri("/Photogallery.xaml?SelectedIndex=" + listBoxPhoto.SelectedIndex, UriKind.Relative));
}
//Photogallery.xaml.cs
// Reference to App
private App app = App.Current as App;
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
base.OnNavigatedTo(e);
IDictionary<string, string> parameters = this.NavigationContext.QueryString;
if (parameters.ContainsKey("SelectedIndex"))
{
app.selectedImageIndex = Int32.Parse(parameters["SelectedIndex"]);
}
else
{
app.selectedImageIndex = 0;
}
LoadImage();
}
private void LoadImage()
{
BitmapImage bitmapImage = new BitmapImage();
bitmapImage.UriSource=new Uri(app.albumImages[app.selectedImageIndex].content, UriKind.RelativeOrAbsolute);
image.Source = bitmapImage;
}`
为了满足您的要求,您还必须使照片集全局可用于 Photogallery 页面。为此,可以从 MainPage.xaml.cs 页面将 photoCollection(用于绑定到列表框)的副本分配给 App.xaml 的 albumImages.cs
注意:问题中的代码进行了一些更改(我不确定是谁做的),但代码非常接近工作。