2016-07-30 188 views
1

我的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; } 
    } 
} 

回答

0

我想通了。我的問題在於我試圖將數據傳遞到頁面本身的方式。而不是使用DataContext = Items;並嘗試以這種方式訪問​​數據。我相反​​爲GridView設置了直接ItemsSource

最終的結果是簡單地改變DataContext = ItemsitemGridView.ItemsSource = Items;

0

無一個好的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]將確保您得到一個肯定能夠工作的答案。 –