将可观察集合绑定到GridView

将可观察集合绑定到GridView

问题描述:

我的UWP需要有一个“收藏夹”页面,允许用户重新排序并将数据保存在页面上。最初,我的数据来自一个大的JSON文件,它使用Newtonsoft的Json.net进行反序列化,并存储在一个Dictionary中,然后填充公共ObservableCollection。将可观察集合绑定到GridView

这就是我现在迷失的地方,将ObservableCollection设置为DataContext,然后在XAML代码中使用数据作为绑定来填充每个项目所需的所有标题,字幕和图像。 理论上这应该可以工作,但是在我的试验和测试中,页面保持空白,而幕后的所有C#代码都使它看起来应该被填充。

我不知道为什么页面没有填满我转向所有人的集体帮助。

P.S:我真的不关心这段代码的整洁,我只是想让它工作。


XAML文件

<Page 
x:Name="pageRoot" 
x:Class="Melbourne_Getaway.FavouritesPage" 
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
xmlns:local="using:Melbourne_Getaway" 
xmlns:data="using:Melbourne_Getaway.Data" 
xmlns:common="using:Melbourne_Getaway.Common" 
xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
mc:Ignorable="d"> 

<Page.Resources> 
    <x:String x:Key="AppName">Favourites</x:String> 
</Page.Resources> 

<!-- 
    This grid acts as a root panel for the page that defines two rows: 
    * Row 0 contains the back button and page title 
    * Row 1 contains the rest of the page layout 
--> 
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"> 
    <Grid.ChildrenTransitions> 
     <TransitionCollection> 
      <EntranceThemeTransition /> 
     </TransitionCollection> 
    </Grid.ChildrenTransitions> 
    <Grid.RowDefinitions> 
     <RowDefinition Height="140" /> 
     <RowDefinition Height="*" /> 
    </Grid.RowDefinitions> 

    <GridView 
     x:Name="itemGridView" 
     AutomationProperties.AutomationId="ItemsGridView" 
     AutomationProperties.Name="Items" 
     TabIndex="1" 
     Grid.RowSpan="2" 
     Padding="60,136,116,46" 
     SelectionMode="None" 
     IsSwipeEnabled="false" 
     CanReorderItems="True" 
     CanDragItems="True" 
     AllowDrop="True" 
     ItemsSource="{Binding Items}"> 
     <GridView.ItemTemplate> 
      <DataTemplate> 
       <Grid HorizontalAlignment="Left" Width="250" Height="107"> 
        <Border Background="{ThemeResource ListViewItemPlaceholderBackgroundThemeBrush}"> 
         <Image Source="{Binding ImagePath}" Stretch="UniformToFill" AutomationProperties.Name="{Binding Title}" /> 
        </Border> 
        <StackPanel VerticalAlignment="Bottom" Background="{ThemeResource ListViewItemOverlayBackgroundThemeBrush}"> 
         <TextBlock Text="{Binding Title}" Foreground="{ThemeResource ListViewItemOverlayForegroundThemeBrush}" Style="{StaticResource BaseTextBlockStyle}" Height="30" Margin="15,0,15,0" FontWeight="SemiBold" /> 
         <TextBlock Text="{Binding Group}" Foreground="{ThemeResource ListViewItemOverlaySecondaryForegroundThemeBrush}" Style="{StaticResource BaseTextBlockStyle}" TextWrapping="NoWrap" Margin="15,-15,15,10" FontSize="12" /> 
        </StackPanel> 
       </Grid> 
      </DataTemplate> 
     </GridView.ItemTemplate> 
    </GridView> 

    <!-- Back button and page title --> 
    <Grid> 
     <Grid.ColumnDefinitions> 
      <ColumnDefinition Width="120" /> 
      <ColumnDefinition Width="*" /> 
     </Grid.ColumnDefinitions> 
     <Button x:Name="backButton" Margin="39,59,39,0" Command="{Binding NavigationHelper.GoBackCommand, ElementName=pageRoot}" 
        Style="{StaticResource NavigationBackButtonNormalStyle}" 
        VerticalAlignment="Top" 
        AutomationProperties.Name="Back" 
        AutomationProperties.AutomationId="BackButton" 
        AutomationProperties.ItemType="Navigation Button" /> 
     <TextBlock x:Name="pageTitle" Text="{StaticResource AppName}" Style="{StaticResource HeaderTextBlockStyle}" Grid.Column="1" 
        IsHitTestVisible="false" TextWrapping="NoWrap" VerticalAlignment="Bottom" Margin="0,0,30,40" /> 
    </Grid> 
</Grid> 


CS文件

using Melbourne_Getaway.Common; 
using Melbourne_Getaway.Data; 
using Newtonsoft.Json; 
using System; 
using System.Collections.Generic; 
using System.Collections.ObjectModel; 
using Windows.Storage; 
using Windows.UI.Popups; 
using Windows.UI.Xaml.Controls; 
using Windows.UI.Xaml.Navigation; 

namespace Melbourne_Getaway 
{ 
    public sealed partial class FavouritesPage : Page 
    { 
     public ObservableCollection<ItemData> Items { get; set; } 

     private ObservableDictionary defaultViewModel = new ObservableDictionary(); 
     private NavigationHelper navigationHelper; 
     private RootObject jsonLines; 
     private StorageFile fileFavourites; 
     private Dictionary<string, ItemData> ItemData = new Dictionary<string, ItemData>(); 

     public FavouritesPage() 
     { 
      loadJson(); 
      getFavFile(); 

      this.InitializeComponent(); 
      this.navigationHelper = new NavigationHelper(this); 
      this.navigationHelper.LoadState += navigationHelper_LoadState; 
     } 

     private void setupObservableCollection() 
     { 
      Items = new ObservableCollection<ItemData>(ItemData.Values); 
      DataContext = Items; 
     } 

     private async void loadJson() 
     { 
      var file = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///DataModel/SampleData.json")); 
      string lines = await FileIO.ReadTextAsync(file); 
      jsonLines = JsonConvert.DeserializeObject<RootObject>(lines); 
      feedItems(); 
     } 

     private async void getFavFile() 
     { 
      Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder; 
      fileFavourites = await storageFolder.GetFileAsync("MelbGetaway.fav"); 
     } 

     private async void feedItems() 
     { 
      if (await FileIO.ReadTextAsync(fileFavourites) != "") 
      { 
       foreach (var line in await FileIO.ReadLinesAsync(fileFavourites)) 
       { 
        foreach (var Group in jsonLines.Groups) 
        { 
         foreach (var Item in Group.Items) 
         { 
          if (Item.UniqueId == line) 
          { 
           var storage = new ItemData() 
           { 
            Title = Item.Title, 
            UniqueID = Item.UniqueId, 
            ImagePath = Item.ImagePath, 
            Group = Group.Title 
           }; 
           ItemData.Add(storage.UniqueID, storage); 
          } 
         } 
        } 
       } 
      } 
      else 
      {//should only execute if favourites file is empty, first time use? 
       foreach (var Group in jsonLines.Groups) 
       { 
        foreach (var Item in Group.Items) 
        { 
         var storage = new ItemData() 
         { 
          Title = Item.Title, 
          UniqueID = Item.UniqueId, 
          ImagePath = Item.ImagePath, 
          Group = Group.Title 
         }; 
         ItemData.Add(storage.UniqueID, storage); 
         await FileIO.AppendTextAsync(fileFavourites, Item.UniqueId + "\r\n"); 
        } 
       } 
      } 
      setupObservableCollection(); 
     } 

     public ObservableDictionary DefaultViewModel 
     { 
      get { return this.defaultViewModel; } 
     } 

     #region NavigationHelper loader 

     public NavigationHelper NavigationHelper 
     { 
      get { return this.navigationHelper; } 
     } 

     private async void MessageBox(string Message) 
     { 
      MessageDialog dialog = new MessageDialog(Message); 
      await dialog.ShowAsync(); 
     } 

     private async void navigationHelper_LoadState(object sender, LoadStateEventArgs e) 
     { 
      var sampleDataGroups = await SampleDataSource.GetGroupsAsync(); 
      this.defaultViewModel["Groups"] = sampleDataGroups; 
     } 

     #endregion NavigationHelper loader 

     #region NavigationHelper registration 

     protected override void OnNavigatedFrom(NavigationEventArgs e) 
     { 
      navigationHelper.OnNavigatedFrom(e); 
     } 

     protected override void OnNavigatedTo(NavigationEventArgs e) 
     { 
      navigationHelper.OnNavigatedTo(e); 
     } 

     #endregion NavigationHelper registration 
    } 

    public class ItemData 
    { 
     public string UniqueID { get; set; } 
     public string Title { get; set; } 
     public string Group { get; set; } 
     public string ImagePath { get; set; } 
    } 
} 

我想通了。我的问题在于我试图将数据传递到页面本身的方式。而不是使用DataContext = Items;并尝试以这种方式访问​​数据。我相反​​为GridView设置了直接ItemsSource

最终的结果是简单地改变DataContext = ItemsitemGridView.ItemsSource = Items;

无一个好的Minimal, Complete, and Verifiable code example这是不可能的,肯定知道什么是错的。然而,一个明显的错误会出现在你的代码:

private void setupObservableCollection() 
{ 
    Items = new ObservableCollection<ItemData>(ItemData.Values); 
    DataContext = Items; 
} 

在XAML中,绑定到{Binding Items}。将DataContext设置为Items属性值,正确的绑定实际上只是{Binding}

或者,如果您想保持XAML的方式,您必须改为设置DataContext = this;。当然,如果你这样做,那么你会遇到问题,你似乎没有提高INotifyPropertyChanged.PropertyChanged,甚至实现该接口。如果您确定该属性将在调用InitializeComponent()方法之前设置,您可以避开,但是在您显示的代码中看起来不是这种情况。

所以,如果你想设置为{Binding Items}你结合还需要实现INotifyPropertyChanged,并确保你提高PropertyChanged事件与属性名"Items"当你真正设置该属性。

如果上述内容不能解决您的问题,请通过提供可靠地再现问题的良好MCVE来改善问题。

+0

我已经改变了的DataContext只是'{结合}'如你所说,但它并没有改变什么(除非我失去了一些东西)。我也不特别想实现你建议的PropertyChanged解决方案,因为我只是不知道它是干什么的或者干脆干活的。我将尽快将这个问题尽快排除 – Haybale100

+0

如果您要编写WPF程序,您必须**了解有关INotifyPropertyChanged的信息并能够实现它。没有它,你将无法获得任何不平凡的绑定。就目前的问题而言,我只能根据您在问题中发布的内容提供建议。如果更改绑定到'ItemsSource =“{绑定}”'没有解决问题,那么还有其他事情在您发布的代码中不明显。解决这个问题,使其包含一个好的[mcve]将确保您得到一个肯定能够工作的答案。 –