title: Deserialization of JSON Object to ObservableCollection<T> and binding it to a GridView Or ListView in a MVVM (Template 10) On App Lauch
body: <p>I am a newbie to MVVM for UWP, I am in a bit of a quagmire, I want to bind a Deserialized JSON Object to a GridView or ListView but I am faced with this scenario.</p>
  
  <p>When I start the App the Deserialization runs and but the GridView is empty, In order for me to see the deserialized data, i have to navigate to another page then come back to see the deserialized data. this is also the case for binding to a ListView.</p>
  
  <p>Key things to note.</p>
  
  <p>In both Grid and List Views, I am using x:Bind to bind ViewModel.ObservableCollectionList to it.</p>
  
  <p>I am calling the Deserialization method in the Constructor of the MainPage.cs</p>
  
  <p>Could someone help me please.</p>
  
  <p>P.O.Aliu</p>
  
  <p>I have attached the ViewModel for mainpage, the mainpage.xaml and mainpage.xaml.cs</p>
  
  <pre><code>using Newtonsoft.Json;
  using System;
  using System.Collections.Generic;
  using System.Collections.ObjectModel;
  using System.Diagnostics;
  using System.IO;
  using System.Linq;
  using System.Threading.Tasks;
  using Template10.Common;
  using Template10.Mvvm;
  using Template10.Services.NavigationService;
  using Tymly_Revamped.Models;
  using Tymly_Revamped.Views;
  using Windows.Storage;
  using Windows.UI.Xaml.Controls;
  using Windows.UI.Xaml.Navigation;
  
  namespace Tymly_Revamped.ViewModels
  {
      public class MainPageViewModel : ViewModelBase
      {
          public ObservableCollection&lt;Tymly&gt; TymlysList =&gt; new ObservableCollection&lt;Tymly&gt;();
          public static MainPageViewModel _mainPageViewModel;
          public Tymly SelectedTymly { get; set; }
  
      //Storage Folders for Data
      private StorageFolder _localFolder = null;
      private StorageFolder localCacheFolder = null;
      private StorageFolder roamingFolder = null;
      private StorageFolder tempFolder = null;
  
      private string _filename = "TymlyFiles";
      private ObservableCollection&lt;Tymly&gt; _deserializedModel = new ObservableCollection&lt;Tymly&gt;();
  
      public MainPageViewModel()
      {
          _localFolder = ApplicationData.Current.LocalFolder;
          localCacheFolder = ApplicationData.Current.LocalCacheFolder;
          roamingFolder = ApplicationData.Current.RoamingFolder;
          tempFolder = ApplicationData.Current.TemporaryFolder;
          _mainPageViewModel = this;
  
          // TymlysList = TymlyManager.GetTymlys();
          SelectedTymly = new Tymly();
          // ReadFromJson();
      }
  
      public async void tymlysGrid_ItemClick(object sender, ItemClickEventArgs e)
      {
          var tymly = (Tymly)e.ClickedItem;
          SelectedTymly = tymly;
          SessionState.Add(nameof(SelectedTymly), SelectedTymly);
          await WindowWrapper.Current().NavigationServices.FirstOrDefault().NavigateAsync(typeof(SelectedTymly), nameof(SelectedTymly));
      }
  
      public override async Task OnNavigatedToAsync(object parameter, NavigationMode mode, IDictionary&lt;string, object&gt; suspensionState)
      {
          ReadFromJson();
          SessionState.Remove(nameof(SelectedTymly));
          var newTymly = parameter as string;
          if (newTymly != null &amp;&amp; SessionState.ContainsKey(newTymly))
          {
              var tym = SessionState.Get&lt;Tymly&gt;(newTymly);
  
              if (tym != null &amp;&amp; !TymlysList.Contains(tym) &amp;&amp; !tym.Location.Equals(string.Empty))
              {
                  TymlysList.Add(tym);
                  WriteToJson();
              }
  
          }
          await Task.CompletedTask;
      }
  
      public override async Task OnNavigatedFromAsync(IDictionary&lt;string, object&gt; suspensionState, bool suspending)
      {
          if (suspending)
          {
              //suspensionState[nameof(Value)] = Value;
              suspensionState[nameof(SelectedTymly)] = SelectedTymly;
          }
          await Task.CompletedTask;
      }
  
      public override async Task OnNavigatingFromAsync(NavigatingEventArgs args)
      {
          args.Cancel = false;
          await Task.CompletedTask;
      }
  
      public void GotoSelectedTymlyPage() =&gt;
          NavigationService.Navigate(typeof(SelectedTymly), SelectedTymly);
  
      public void GotoSettings() =&gt;
          NavigationService.Navigate(typeof(SettingsPage), 0);
  
      public void GotoPrivacy() =&gt;
          NavigationService.Navigate(typeof(SettingsPage), 1);
  
      public void GotoAbout() =&gt;
          NavigationService.Navigate(typeof(SettingsPage), 2);
  
  
  
      //Data Persistence
      public async Task&lt;string&gt; SerializeTymlyToJson&lt;T&gt;(ObservableCollection&lt;T&gt; observableCollection, string fileName)
      {
          try
          {
              var Folder = Windows.Storage.ApplicationData.Current.LocalFolder;
  
              var file = await Folder.CreateFileAsync(fileName + ".json", CreationCollisionOption.ReplaceExisting);
              var data = await file.OpenStreamForWriteAsync();
  
              using (StreamWriter streamWriter = new StreamWriter(data))
              {
                  var serializedFile = JsonConvert.SerializeObject(observableCollection, Formatting.Indented);
                  streamWriter.Write(serializedFile);
              }
              return fileName;
          }
          catch (Exception e)
          {
              Debug.WriteLine(e.Message);
              Debug.WriteLine("It Did not work");
              throw e;
  
          }
      }
  
      public async Task&lt;ObservableCollection&lt;T&gt;&gt; DeserializeJsonToTymly&lt;T&gt;(string fileName)
      {
          try
          {
              ObservableCollection&lt;T&gt; contacts = new ObservableCollection&lt;T&gt;();
              var Folder = Windows.Storage.ApplicationData.Current.LocalFolder;
              var file = await Folder.GetFileAsync(fileName + ".json");
              var data = await file.OpenReadAsync();
  
              using (StreamReader streamReader = new StreamReader(data.AsStream()))
              {
                  string text = streamReader.ReadToEnd();
                  ObservableCollection&lt;T&gt; contact = JsonConvert.DeserializeObject&lt;ObservableCollection&lt;T&gt;&gt;(text);
                  foreach (var con in contact)
                  {
                      contacts.Add(con);
                  }
              }
              return contacts;
          }
          catch (Exception e)
          {
  
              throw e;
          }
      }
  
      public async void WriteToJson()
      {
          try
          {
              _filename = await SerializeTymlyToJson&lt;Tymly&gt;(TymlysList, "TymlyFiles");
          }
          catch (Exception e)
          {
              Debug.WriteLine(e.Message);
              Debug.WriteLine("No WAY");
              throw e;
          }
      }
      public async void ReadFromJson()
      {
          try
          {
              _deserializedModel = await DeserializeJsonToTymly&lt;Tymly&gt;(_filename);
              //TymlysList.Clear();
              foreach (var tymly in _deserializedModel)
              {
                  Debug.WriteLine("Done One");
                  TymlysList.Add(tymly);
              }
              Debug.WriteLine("Read Json");
  
          }
          catch (Exception e)
          {
              Debug.WriteLine(e.Message);
              Debug.WriteLine("ReadFromJSon");
          }
      }   
  }
  </code></pre>
  
  <p>}</p>
  
  <pre><code>&lt;Page x:Class="Tymly_Revamped.Views.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:Behaviors="using:Template10.Behaviors"
    xmlns:Core="using:Microsoft.Xaml.Interactions.Core"
    xmlns:Interactivity="using:Microsoft.Xaml.Interactivity"
    xmlns:controls="using:Template10.Controls"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:local="using:Tymly_Revamped.Views"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:tm="using:Tymly_Revamped.Models"
    xmlns:vm="using:Tymly_Revamped.ViewModels" mc:Ignorable="d"&gt;
  
  &lt;Page.DataContext&gt;
      &lt;vm:MainPageViewModel x:Name="ViewModel" /&gt;
  &lt;/Page.DataContext&gt;
  &lt;!--&lt;Page.Resources&gt;
      &lt;CollectionViewSource x:Name="TymlyListViewSource"
                            Source="{x:Bind ViewModel.TymlysList}"
                            IsSourceGrouped="False"/&gt;
  &lt;/Page.Resources&gt;--&gt;
  
  &lt;RelativePanel Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"&gt;
  
      &lt;VisualStateManager.VisualStateGroups&gt;
          &lt;VisualStateGroup x:Name="AdaptiveVisualStateGroup" CurrentStateChanged="AdaptiveVisualStateGroup_OnCurrentStateChanged"&gt;
              &lt;VisualState x:Name="VisualStateNarrow"&gt;
                  &lt;VisualState.StateTriggers&gt;
                      &lt;AdaptiveTrigger MinWindowWidth="{StaticResource NarrowMinWidth}" /&gt;
                  &lt;/VisualState.StateTriggers&gt;
                  &lt;VisualState.Setters&gt;
                      &lt;Setter Target="tymlysGrid.Visibility" Value="Collapsed"/&gt;
                      &lt;Setter Target="tymlysListView.Visibility" Value="Visible"/&gt;
                  &lt;/VisualState.Setters&gt;
              &lt;/VisualState&gt;
              &lt;VisualState x:Name="VisualStateNormal"&gt;
                  &lt;VisualState.StateTriggers&gt;
                      &lt;AdaptiveTrigger MinWindowWidth="{StaticResource NormalMinWidth}" /&gt;
                  &lt;/VisualState.StateTriggers&gt;
                  &lt;VisualState.Setters&gt;
                      &lt;Setter Target="tymlysGrid.Visibility" Value="Visible"/&gt;
                      &lt;Setter Target="tymlysListView.Visibility" Value="Collapsed"/&gt;
                  &lt;/VisualState.Setters&gt;
              &lt;/VisualState&gt;
              &lt;VisualState x:Name="VisualStateWide"&gt;
                  &lt;VisualState.StateTriggers&gt;
                      &lt;AdaptiveTrigger MinWindowWidth="{StaticResource WideMinWidth}" /&gt;
                  &lt;/VisualState.StateTriggers&gt;
                  &lt;VisualState.Setters&gt;
                      &lt;Setter Target="tymlysGrid.Visibility" Value="Visible"/&gt;
                      &lt;Setter Target="tymlysListView.Visibility" Value="Collapsed"/&gt;
                  &lt;/VisualState.Setters&gt;
              &lt;/VisualState&gt;
          &lt;/VisualStateGroup&gt;
      &lt;/VisualStateManager.VisualStateGroups&gt;
  
      &lt;controls:PageHeader x:Name="pageHeader" RelativePanel.AlignLeftWithPanel="True"
                           RelativePanel.AlignRightWithPanel="True" Frame="{x:Bind Frame}"
                           RelativePanel.AlignTopWithPanel="True" Text="TYMLYS" Foreground="Black" FontFamily="mononoki" FontWeight="Bold" Content="TYMLYS" BorderBrush="Black" BorderThickness="3"&gt;
          &lt;controls:PageHeader.Background&gt;
              &lt;LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0"&gt;
                  &lt;GradientStop Color="Black" Offset="0"/&gt;
                  &lt;GradientStop Color="#FF25E67D" Offset="1"/&gt;
              &lt;/LinearGradientBrush&gt;
          &lt;/controls:PageHeader.Background&gt;
  
          &lt;!--  secondary commands  --&gt;
          &lt;controls:PageHeader.SecondaryCommands&gt;
              &lt;AppBarButton Click="{x:Bind ViewModel.GotoSettings}" Label="Settings" /&gt;
              &lt;AppBarButton Click="{x:Bind ViewModel.GotoPrivacy}" Label="Privacy" /&gt;
              &lt;AppBarButton Click="{x:Bind ViewModel.GotoAbout}" Label="About" /&gt;
          &lt;/controls:PageHeader.SecondaryCommands&gt;
  
      &lt;/controls:PageHeader&gt;
  
      &lt;GridView x:Name="tymlysGrid"
                RelativePanel.Below="pageHeader"
                RelativePanel.AlignLeftWithPanel="True"
                RelativePanel.AlignRightWithPanel="True"
                RelativePanel.AlignBottomWithPanel="True"
                IsItemClickEnabled="True"
                ItemsSource="{x:Bind ViewModel.TymlysList, Mode=OneWay}"
                ItemClick="{x:Bind ViewModel.tymlysGrid_ItemClick}" ScrollViewer.VerticalScrollBarVisibility="Hidden"&gt;
          &lt;GridView.ItemContainerStyle&gt;
              &lt;Style TargetType="GridViewItem"&gt;
                  &lt;Setter Property="MinHeight" Value="150"&gt;&lt;/Setter&gt;
                  &lt;Setter Property="MaxHeight" Value="300"&gt;&lt;/Setter&gt;
                  &lt;Setter Property="MinWidth" Value="320"&gt;&lt;/Setter&gt;
                  &lt;Setter Property="MaxWidth" Value="480"&gt;&lt;/Setter&gt;
              &lt;/Style&gt;
          &lt;/GridView.ItemContainerStyle&gt;
          &lt;GridView.ItemTemplate&gt;
              &lt;DataTemplate x:Name="TymlyTemplate" x:DataType="tm:Tymly"&gt;
                  &lt;Grid x:Name="Main" Style="{ThemeResource GridViewInnerGrid}"&gt;
                      &lt;Grid.ColumnDefinitions&gt;
                          &lt;ColumnDefinition Width="2*"/&gt;
                          &lt;ColumnDefinition Width="1.5*"/&gt;
                      &lt;/Grid.ColumnDefinitions&gt;
  
                      &lt;Grid Grid.Column="0"&gt;
                          &lt;Grid.RowDefinitions&gt;
                              &lt;RowDefinition Height="4*"/&gt;
                              &lt;RowDefinition Height="2*"/&gt;
                              &lt;RowDefinition Height="2*"/&gt;
                          &lt;/Grid.RowDefinitions&gt;
                          &lt;TextBlock Grid.Column="0" Grid.Row="0"
                  Style="{ThemeResource MediumText}"
                      Text="{x:Bind Location}"  HorizontalAlignment="Left" VerticalAlignment="Center" &gt;&lt;/TextBlock&gt;
                          &lt;TextBlock Grid.Column="0" Grid.Row="1"
                  Style="{ThemeResource SmallText}"
                      Text="{x:Bind Date}"  HorizontalAlignment="Left" VerticalAlignment="Center"&gt;&lt;/TextBlock&gt;
                          &lt;TextBlock  Grid.Column="0" Grid.Row="2" Style="{ThemeResource SmallText}" Text="{x:Bind Time}"  HorizontalAlignment="Left" VerticalAlignment="Center"&gt;&lt;/TextBlock&gt;
                      &lt;/Grid&gt;
                      &lt;Viewbox Grid.Column="1" HorizontalAlignment="Center" VerticalAlignment="Center" Width="100" Height="100"&gt;
                          &lt;Canvas Width="100" Height="100" HorizontalAlignment="Center" VerticalAlignment="Center"&gt;
                              &lt;Ellipse Fill="Green"  Width="100" Height="100" HorizontalAlignment="Center" VerticalAlignment="Center" /&gt;
                              &lt;Path
                          Data="{x:Bind MapIcon}"
                          Fill="Black" Width="100" Height="100" HorizontalAlignment="Center" VerticalAlignment="Center" RenderTransformOrigin="0.5,0.5"
                          &gt;
                                  &lt;Path.RenderTransform&gt;
                                      &lt;CompositeTransform TranslateX="70" TranslateY="70" ScaleX="2" ScaleY="2"/&gt;
                                  &lt;/Path.RenderTransform&gt;
                              &lt;/Path&gt;
                          &lt;/Canvas&gt;
  
                      &lt;/Viewbox&gt;
                  &lt;/Grid&gt;
              &lt;/DataTemplate&gt;
          &lt;/GridView.ItemTemplate&gt;
      &lt;/GridView&gt;
  
      &lt;ListView x:Name="tymlysListView"
                Style="{ThemeResource NarrowListView}"
                RelativePanel.Below="pageHeader"
                IsItemClickEnabled="True"
                ItemsSource="{x:Bind ViewModel.TymlysList, Mode=OneWay}"
                ItemClick="{x:Bind ViewModel.tymlysGrid_ItemClick}" ScrollViewer.VerticalScrollBarVisibility="Hidden" Visibility="Collapsed"&gt;
          &lt;ListView.ItemContainerStyle&gt;
              &lt;Style TargetType="ListViewItem"&gt;
                  &lt;Setter Property="MinHeight" Value="120"&gt;&lt;/Setter&gt;
                  &lt;Setter Property="MaxHeight" Value="250"&gt;&lt;/Setter&gt;
                  &lt;Setter Property="MinWidth" Value="320"&gt;&lt;/Setter&gt;
                  &lt;Setter Property="MaxWidth" Value="640"&gt;&lt;/Setter&gt;
                  &lt;Setter Property="Padding" Value="10"&gt;&lt;/Setter&gt;
              &lt;/Style&gt;
          &lt;/ListView.ItemContainerStyle&gt;
          &lt;ListView.ItemTemplate&gt;
              &lt;DataTemplate x:Name="TymlyTemplate1" x:DataType="tm:Tymly"&gt;
                  &lt;Grid x:Name="Main" Style="{ThemeResource ListViewInnerGrid}"&gt;
                      &lt;Grid.ColumnDefinitions&gt;
                          &lt;ColumnDefinition Width="2*"/&gt;
                          &lt;ColumnDefinition Width="1.5*"/&gt;
                      &lt;/Grid.ColumnDefinitions&gt;
  
                      &lt;Grid Grid.Column="0"&gt;
                          &lt;Grid.RowDefinitions&gt;
                              &lt;RowDefinition Height="3*"/&gt;
                              &lt;RowDefinition Height="2*"/&gt;
                              &lt;RowDefinition Height="2*"/&gt;
                          &lt;/Grid.RowDefinitions&gt;
                          &lt;TextBlock Grid.Column="0" Grid.Row="0"
                  Style="{ThemeResource MediumText}"
                      Text="{x:Bind Location}"  HorizontalAlignment="Left" VerticalAlignment="Center" Margin="5,0" &gt;&lt;/TextBlock&gt;
                          &lt;TextBlock Grid.Column="0" Grid.Row="1" Margin="5,0"
                  Style="{ThemeResource SmallText}"
                      Text="{x:Bind Date}"  HorizontalAlignment="Left" VerticalAlignment="Center"&gt;&lt;/TextBlock&gt;
                          &lt;TextBlock  Grid.Column="0" Grid.Row="2" Style="{ThemeResource SmallText}" Text="{x:Bind Time}"  HorizontalAlignment="Left" VerticalAlignment="Center" Margin="5,0"&gt;&lt;/TextBlock&gt;
                      &lt;/Grid&gt;
                      &lt;Viewbox Grid.Column="1" HorizontalAlignment="Center" VerticalAlignment="Center" Width="100" Height="100"&gt;
                          &lt;Canvas Width="100" Height="100" HorizontalAlignment="Center" VerticalAlignment="Center" Margin="5"&gt;
                              &lt;Ellipse Fill="Green"  Width="100" Height="100" HorizontalAlignment="Center" VerticalAlignment="Center" /&gt;
                              &lt;Path
                          Data="{x:Bind MapIcon}"
                          Fill="Black" Width="100" Height="100" HorizontalAlignment="Center" VerticalAlignment="Center" RenderTransformOrigin="0.5,0.5"
                          &gt;
                                  &lt;Path.RenderTransform&gt;
                                      &lt;CompositeTransform TranslateX="70" TranslateY="70" ScaleX="2" ScaleY="2"/&gt;
                                  &lt;/Path.RenderTransform&gt;
                              &lt;/Path&gt;
                          &lt;/Canvas&gt;
  
                      &lt;/Viewbox&gt;
                  &lt;/Grid&gt;
              &lt;/DataTemplate&gt;
          &lt;/ListView.ItemTemplate&gt;
      &lt;/ListView&gt;
  &lt;/RelativePanel&gt;
  </code></pre>
  
  <p></p>
  
  <pre><code>using Windows.UI.Xaml;
  using Windows.UI.Xaml.Navigation;
  
  
  namespace Tymly_Revamped.Views
  {
      public sealed partial class MainPage
      {
          public MainPage()
          {
              InitializeComponent();
              NavigationCacheMode = NavigationCacheMode.Enabled;
  
          }
  
          private void AdaptiveVisualStateGroup_OnCurrentStateChanged(object sender, VisualStateChangedEventArgs e)
          {
              if (e.NewState == VisualStateNarrow)
              {
                  tymlysGrid.Visibility = Visibility.Collapsed;
                  tymlysListView.Visibility = Visibility.Visible;
              }
              else if (e.NewState == VisualStateNormal || e.NewState == VisualStateWide)
              {
                  tymlysGrid.Visibility = Visibility.Visible;
                  tymlysListView.Visibility = Visibility.Collapsed;
              }
          }
      }
  }
  </code></pre>