0
votes

I need help...

So essentially I've been watching WP 8.1 development tutorials and there was a tutorial with the standard HUB template.

So I tried to configure this template for my own use. I have a JSON file with all the data I need (apartments) which I want list now on my page. I "recreated" the SampleDataSource which is in my app just DataSource. I think everything is OK with the data and now comes the problem with translating this data and binding it to XAML. I don't really know why it isn't working as I have just tried to change the paramters which work in the template (provided by the SDK). Could you guys help me or give me some directions where can I find example for doing this.

If someone would be willing to help or skype/TW with me just to show me the structure and what I have to do, I would be grateful as I would then know how this basically translates and works so I could work on other sections of the project! Have bitcoins as a reward! :)

Thx in advance.

EDIT: Add Github repo: https://github.com/lklancir/zimmerfrei_wp/tree/master/ZimmerFrei_v0.1

Here is the DataSource.cs:

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Data.Json;
using Windows.Storage;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Media.Imaging;

namespace ZimmerFrei.Data {

public class ApartmentData
{
    public ApartmentData(String id, String name, String description, String capacity, String stars, String address, String email, String phone, String phone2, String rating, String lat, String lng, String price, String cover_photo, String owner_id, String type_id, String city_id)
    {
        this.Id = id;
        this.Name = name;
        this.Description = description;
        this.Capacity = capacity;
        this.Stars = stars;
        this.Address = address;
        this.Email = email;
        this.Phone = phone;
        this.Phone2 = phone2;
        this.Rating = rating;
        this.Lat = lat;
        this.Lng = lng;
        this.Price = price;
        this.Cover_photo = cover_photo;
        this.Owner_id = owner_id;
        this.Type_id = type_id;
        this.City_id = city_id;


    }

    public string Id { get; private set; }
    public string Name { get; private set; }
    public string Description { get; private set; }
    public string Capacity { get; private set; }
    public string Stars { get; private set; }
    public string Address { get; private set; }
    public string Email { get; private set; }
    public string Phone { get; private set; }
    public string Phone2 { get; private set; }
    public string Rating { get; private set; }
    public string Lat { get; private set; }
    public string Lng { get; private set; }
    public string Price { get; private set; }
    public string Cover_photo { get; private set; }
    public string Owner_id { get; private set; }
    public string Type_id { get; private set; }
    public string City_id { get; private set; }

    public override string ToString()
    {
        return this.Name;
    }
}



public sealed class DataSource
{
    private static DataSource _dataSource = new DataSource();

    private ObservableCollection<ApartmentData> _apartments = new ObservableCollection<ApartmentData>();

    public ObservableCollection<ApartmentData> Apartments
    {
        get { return this._apartments; }
    }

    public static async Task<IEnumerable<ApartmentData>> GetApartmentsAsync()
    {   
        await _dataSource.GetDataAsync();

        return _dataSource.Apartments;
    }

    public static async Task<ApartmentData> GetApartmentAsync(string id)
    {
        await _dataSource.GetDataAsync();
        var matches = _dataSource.Apartments.Where((apartment) => apartment.Id.Equals(id));
        if (matches.Count() == 1) return matches.First();
        return null;
    }



    private async Task GetDataAsync()
    {
        if (this._apartments.Count != 0)
            return;

        Uri dataUri = new Uri("ms-appx:///DataModel/Apartments.json");
        StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(dataUri);
        string jsonText = await FileIO.ReadTextAsync(file);
        JsonObject jsonObject = JsonObject.Parse(jsonText);
        JsonArray jsonArray = jsonObject["apartments"].GetArray();

        foreach (JsonValue apartmentValue in jsonArray)
        {
            JsonObject apartmentObject = apartmentValue.GetObject();
            ApartmentData apartment = new ApartmentData(apartmentObject["Id"].GetString(),
                                                        apartmentObject["Name"].GetString(),
                                                        apartmentObject["Description"].GetString(),
                                                        apartmentObject["Capacity"].GetString(),
                                                        apartmentObject["Stars"].GetString(),
                                                        apartmentObject["Address"].GetString(),
                                                        apartmentObject["Email"].GetString(),
                                                        apartmentObject["Phone"].GetString(),
                                                        apartmentObject["Phone2"].GetString(),
                                                        apartmentObject["Rating"].GetString(),
                                                        apartmentObject["Lat"].GetString(),
                                                        apartmentObject["Lng"].GetString(),
                                                        apartmentObject["Price"].GetString(),
                                                        apartmentObject["Cover_photo"].GetString(),
                                                        apartmentObject["Owner_id"].GetString(),
                                                        apartmentObject["Type_id"].GetString(),
                                                        apartmentObject["City_id"].GetString());

            this.Apartments.Add(apartment);
        }
    }
}

}

Here is the ListPage.xaml (where I want to write out my data)

<Page
x:Class="ZimmerFrei_v0._1.ListPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:ZimmerFrei_v0._1"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:data="using:ZimmerFrei.Data"
DataContext="{Binding DefaultViewModel, RelativeSource={RelativeSource Self}}"
d:DataContext="{Binding Source={d:DesignData Source=/DataModel/Apartments.json, Type=data:DataSource}}"
mc:Ignorable="d" FontFamily="Global User Interface">


<Page.Resources>


<DataTemplate x:Key="StandardTripleLineItemTemplate">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto"/>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>

        <Border Background="{ThemeResource ListViewItemPlaceholderBackgroundThemeBrush}" Margin="0,9.5,0,0" Grid.Column="0" HorizontalAlignment="Left">
            <Image Source="{Binding Cover_photo}" Stretch="UniformToFill" AutomationProperties.Name="{Binding Title}" Height="79" Width="79"/>
        </Border>
        <StackPanel Grid.Column="1" Margin="14.5,0,0,0">
            <TextBlock Text="{Binding Name}" Style="{ThemeResource ListViewItemTextBlockStyle}" FontFamily="Global User Interface"/>
            <TextBlock Text="{Binding Description}" Style="{ThemeResource ListViewItemContentTextBlockStyle}" Foreground="{ThemeResource PhoneMidBrush}" FontFamily="Global User Interface" />
            <TextBlock Text="{Binding Stars}" Style="{ThemeResource ListViewItemSubheaderTextBlockStyle}" />
        </StackPanel>
    </Grid>
</DataTemplate>

</Page.Resources>

<Grid x:Name="LayoutRoot">
    <Hub x:Name="Hub" x:Uid="Hub" Header="ZimmerFrei">

        <HubSection x:Uid="HubSection" Header="APARTMENTS"
                    DataContext="{Binding Apartments}" >
            <DataTemplate>
                <ListView 
                    AutomationProperties.AutomationId="ItemListViewSection3"
                    AutomationProperties.Name="Items In Group"
                    SelectionMode="None"
                    IsItemClickEnabled="True"
                    ItemsSource="{Binding apartment}"
                    ItemTemplate="{StaticResource StandardTripleLineItemTemplate}"
                    ItemClick="ItemView_ItemClick"
                    ContinuumNavigationTransitionInfo.ExitElementContainer="True">
                </ListView>
            </DataTemplate>
        </HubSection>
    </Hub>
</Grid>

enter image description here

1
What's your concrete problem?khlr
Showing Data on the ListPage.xaml, for example show a list of Apartmetnt from the JSON containing : "Name" , "Description" , "Telephone" for exampleklanc
Could share your DefaultViewModel?user2250152
I think my DataModel is wrong...klanc

1 Answers

1
votes

There are a few issues here:

  • Your ApartmentData class has some properties named like this Cover_photo. This isn't typically the style convention used by C#, so I renamed them to like CoverPhoto.
  • On the same topic, your ApartmentData properties are named like Cover_photo but they are named like cover_photo in the JSON (which is a typical JSON style). You're accessing the JSON keys like this:

    apartmentObject["Cover_photo"].GetString()  // KeyNotFoundException
    

    but it should be:

    apartmentObject["cover_photo"].GetString()
    

    This will work during runtime, but the designer won't execute this code. The designer reads the JSON file and attempts to match keys in the JSON file to properties on the type you have specified, but it won't be able to because the keys and properties don't match. So either you:

    1. Modify the JSON so that the keys match the properties like CoverPhoto.
    2. Annotate your type with the DataContractAttribute. This allows you to specify the mapping between JSON and .NET type with DataMemberAttribute, but mostly because you get JSON serialization/deserialization!

I sent you a pull request with these changes. Also, your design data is huge (~1000 items!). It should only contain ~5 items since you won't be able to see all items in the designer anyway.