【问题标题】:How to reference a nested array in a XAML Binding?如何在 XAML 绑定中引用嵌套数组?
【发布时间】:2018-07-26 22:04:30
【问题描述】:

我有一个基于读取 JSON 文件的复杂数据模型,该文件包含对象、属性和数组的集合。 我正在将我的数据读入一个模型,我用设计时数据填充该模型,并在 XAML 中的 UWP 项目中实例化,如下所示:

<local:UntappdUserInfoSampleData x:Key="data1" />

我想将 ListView 控件的 ItemsSource 设置为我的模型中的一个集合,但我不确定如何在我的数据绑定中引用它。 我的对象模型有这样的结构:

user
  checkins
    items[]
      venue
        venue_name
      comments
      badges
        items[]
          badge_id
          badge_description
          badge_image
            small
            medium
            large

我想在该堆栈中访问 badge_image.small 作为我的 XAML 中的绑定。

我知道如何获取更高级别的数据以获取 checkins.items[]:

            <ListView x:Name="lvRecenCheckins"
                    d:DataContext="{StaticResource data1}"
                    ItemsSource="{Binding checkins.items}"
                    CanDragItems="False"
                    IsItemClickEnabled="True"
                    IsSwipeEnabled="False"
                    SelectionMode="None" ItemTemplate="{StaticResource RecentCheckinsTemplate}" Grid.Row="1"
                    />

但是我怎样才能一直到 checkins.items[].badges.items[] 的项目集合呢?

我可以在后面的代码中找到我想要的集合,以此为例:

        UntappdUserInfoSampleData usersampleinfo = new UntappdUserInfoSampleData();
        string iii2 = usersampleinfo.checkins.items[].badges.items[0].badge_image.small;

我想将不同的 ListView 绑定到 checkins.items[].badges.items[]

我该怎么做?

以下是数据类:

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Serialization;

namespace UntappdExplorer
{

    public class UntappdUserInfoSampleData : User_User        {

        public UntappdUserInfoSampleData() 
        {

            string[] names = this.GetType().GetTypeInfo().Assembly.GetManifestResourceNames();
            Stream stream = this.GetType().GetTypeInfo().Assembly.GetManifestResourceStream("UntappdExplorer.DataModel.ricke_User_info.json");


            string result = String.Empty;
            using (StreamReader reader = new StreamReader(stream))
            {
                result = reader.ReadToEnd();
            }

            var resolver = new DefaultContractResolver(); // Cache for performance
            var Serializersettings = new JsonSerializerSettings
            {
                ContractResolver = resolver,
                Converters = { new IgnoreUnexpectedArraysConverter(resolver) },
            };
            User_RootObject rootJSON = JsonConvert.DeserializeObject<User_RootObject>(result, Serializersettings);

            User_User userinfo = rootJSON.response.user;

            uid = userinfo.uid;
            id = userinfo.id;
            user_name = userinfo.user_name;
            first_name = userinfo.first_name;
            last_name = userinfo.last_name;
            user_avatar = userinfo.user_avatar;
            user_avatar_hd = userinfo.user_avatar_hd;
            user_cover_photo = userinfo.user_cover_photo;
            user_cover_photo_offset = userinfo.user_cover_photo_offset;
            is_private = userinfo.is_private;
            location = userinfo.location;
            url = userinfo.url;
            bio = userinfo.bio;
            is_supporter = userinfo.is_supporter;
            is_moderator = userinfo.is_moderator;
            relationship = userinfo.relationship;
            block_status = userinfo.block_status;
            untappd_url = userinfo.untappd_url;
            account_type = userinfo.account_type;
            stats = userinfo.stats;
            recent_brews = userinfo.recent_brews;
            checkins = userinfo.checkins;
            media = userinfo.media;
            contact = userinfo.contact;
            date_joined = userinfo.date_joined;
            settings = userinfo.settings;

        }


    }

    public class User_User
    {
        public int uid { get; set; }
        public int id { get; set; }
        public string user_name { get; set; }
        public string first_name { get; set; }
        public string last_name { get; set; }
        public string user_avatar { get; set; }
        public string user_avatar_hd { get; set; }
        public string user_cover_photo { get; set; }
        public int user_cover_photo_offset { get; set; }
        public int is_private { get; set; }
        public string location { get; set; }
        public string url { get; set; }
        public string bio { get; set; }
        public int is_supporter { get; set; }
        public int is_moderator { get; set; }
        public string relationship { get; set; }
        public string block_status { get; set; }
        public string untappd_url { get; set; }
        public string account_type { get; set; }
        public User_Stats stats { get; set; }
        public User_RecentBrews recent_brews { get; set; }
        public User_Checkins checkins { get; set; }
        public User_Media2 media { get; set; }
        public List<object> contact { get; set; }
        public string date_joined { get; set; }
        public User_Settings settings { get; set; }
    }



    public class User_RootObject
    {
        public User_Meta meta { get; set; }
        public User_Notifications notifications { get; set; }
        public User_Response response { get; set; }

    }

    public class User_Response
    {
        public User_User user { get; set; }
    }


    public class User_ResponseTime
    {
        public double time { get; set; }
        public string measure { get; set; }
    }

    public class User_InitTime
    {
        public int time { get; set; }
        public string measure { get; set; }
    }

    public class User_Meta
    {
        public int code { get; set; }
        public User_ResponseTime response_time { get; set; }
        public User_InitTime init_time { get; set; }
    }

    public class User_UnreadCount
    {
        public int comments { get; set; }
        public int toasts { get; set; }
        public int friends { get; set; }
        public int messages { get; set; }
        public int venues { get; set; }
        public int veunes { get; set; }
        public int others { get; set; }
        public int news { get; set; }
    }

    public class User_Notifications
    {
        public string type { get; set; }
        public User_UnreadCount unread_count { get; set; }
    }

    public class User_Stats
    {
        public int total_badges { get; set; }
        public int total_friends { get; set; }
        public int total_checkins { get; set; }
        public int total_beers { get; set; }
        public int total_created_beers { get; set; }
        public int total_followings { get; set; }
        public int total_photos { get; set; }
    }

    public class User_Beer
    {
        public int bid { get; set; }
        public string beer_name { get; set; }
        public string beer_label { get; set; }
        public double beer_abv { get; set; }
        public string beer_description { get; set; }
        public string beer_style { get; set; }
        public double auth_rating { get; set; }
        public bool wish_list { get; set; }
    }

    public class User_Contact
    {
        public string twitter { get; set; }
        public string facebook { get; set; }
        public string instagram { get; set; }
        public string url { get; set; }
    }

    public class User_Location
    {
        public string brewery_city { get; set; }
        public string brewery_state { get; set; }
        public double lat { get; set; }
        public double lng { get; set; }
    }

    public class User_Brewery
    {
        public int brewery_id { get; set; }
        public string brewery_name { get; set; }
        public string brewery_slug { get; set; }
        public string brewery_label { get; set; }
        public string country_name { get; set; }
        public User_Contact contact { get; set; }
        public User_Location location { get; set; }
        public int brewery_active { get; set; }
    }

    public class User_Item
    {
        public User_Beer beer { get; set; }
        public User_Brewery brewery { get; set; }
    }

    public class User_RecentBrews
    {
        public int count { get; set; }
        public List<User_Item> items { get; set; }
    }

    public class User_User2
    {
        public int uid { get; set; }
        public string user_name { get; set; }
        public string first_name { get; set; }
        public string last_name { get; set; }
        public string location { get; set; }
        public int is_supporter { get; set; }
        public string url { get; set; }
        public string bio { get; set; }
        public string relationship { get; set; }
        public string user_avatar { get; set; }
        public int is_private { get; set; }
        public List<object> contact { get; set; }
    }

    public class User_Beer2
    {
        public int bid { get; set; }
        public string beer_name { get; set; }
        public string beer_label { get; set; }
        public string beer_style { get; set; }
        public string beer_slug { get; set; }
        public double beer_abv { get; set; }
        public int beer_active { get; set; }
        public bool has_had { get; set; }
        public double auth_rating { get; set; }
        public bool wish_list { get; set; }
    }

    public class User_Contact2
    {
        public string twitter { get; set; }
        public string facebook { get; set; }
        public string instagram { get; set; }
        public string url { get; set; }
    }

    public class User_Location2
    {
        public string brewery_city { get; set; }
        public string brewery_state { get; set; }
        public double lat { get; set; }
        public double lng { get; set; }
    }

    public class User_Brewery2
    {
        public int brewery_id { get; set; }
        public string brewery_name { get; set; }
        public string brewery_slug { get; set; }
        public string brewery_label { get; set; }
        public string country_name { get; set; }
        public User_Contact2 contact { get; set; }
        public User_Location2 location { get; set; }
        public int brewery_active { get; set; }
    }

    public class User_Comments
    {
        public int total_count { get; set; }
        public int count { get; set; }
        public List<object> items { get; set; }
    }

    public class User_User3
    {
        public int uid { get; set; }
        public string user_name { get; set; }
        public string first_name { get; set; }
        public string last_name { get; set; }
        public string bio { get; set; }
        public string location { get; set; }
        public string user_avatar { get; set; }
        public string account_type { get; set; }
        public List<object> venue_details { get; set; }
        public object brewery_details { get; set; }
        public string user_link { get; set; }
    }

    public class User_Item3
    {
        public int uid { get; set; }
        public User_User3 user { get; set; }
        public int like_id { get; set; }
        public bool like_owner { get; set; }
        public string created_at { get; set; }
    }

    public class User_Toasts
    {
        public int total_count { get; set; }
        public int count { get; set; }
        public bool auth_toast { get; set; }
        public List<User_Item3> items { get; set; }
    }

    public class User_Media
    {
        public int count { get; set; }
        public List<object> items { get; set; }
    }

    public class User_Source
    {
        public string app_name { get; set; }
        public string app_website { get; set; }
    }

    public class User_Badges
    {
        public bool retro_status { get; set; }
        public int count { get; set; }
        public List<Item4> items { get; set; }
    }

    public class Item4
    {
        public int badge_id { get; set; }
        public int user_badge_id { get; set; }
        public string badge_name { get; set; }
        public string badge_description { get; set; }
        public string created_at { get; set; }
        public BadgeImage badge_image { get; set; }
    }

    public class BadgeImage
    {
        public string sm { get; set; }
        public string md { get; set; }
        public string lg { get; set; }
    }


    public class User_Item2
    {
        public int checkin_id { get; set; }
        public string created_at { get; set; }
        public string checkin_comment { get; set; }
        public double rating_score { get; set; }
        public User_User2 user { get; set; }
        public User_Beer2 beer { get; set; }
        public User_Brewery2 brewery { get; set; }
        ////public object venue { get; set; }
        public User_Venue venue { get; set; }
        public User_Comments comments { get; set; }
        public User_Toasts toasts { get; set; }
        public User_Media media { get; set; }
        public User_Source source { get; set; }
        public User_Badges badges { get; set; }
    }


    //public class User_Venue
    //{
    //    public int venue_id { get; set; }
    //    public string venue_name { get; set; }
    //    public string venue_slug { get; set; }
    //    public string primary_category { get; set; }
    //    public string parent_category_id { get; set; }
    //    public User_Categories categories { get; set; }
    //    public User_Location3 location { get; set; }
    //    public User_Contact3 contact { get; set; }
    //    public User_Foursquare foursquare { get; set; }
    //    public User_VenueIcon venue_icon { get; set; }
    //    public bool is_verified { get; set; }
    //}

    //public class User_Categories
    //{
    //    public int count { get; set; }
    //    public List<User_Item3> items { get; set; }
    //}

    //public class User_Foursquare
    //{
    //    public string foursquare_id { get; set; }
    //    public string foursquare_url { get; set; }
    //}



    public class User_Pagination
    {
        public string since_url { get; set; }
        public string next_url { get; set; }
        public int max_id { get; set; }
    }

    public class User_Checkins
    {
        public int count { get; set; }
        public List<User_Item2> items { get; set; }
        public User_Pagination pagination { get; set; }
    }

    public class User_Photo
    {
        public string photo_img_sm { get; set; }
        public string photo_img_md { get; set; }
        public string photo_img_lg { get; set; }
        public string photo_img_og { get; set; }
    }

    public class User_User4
    {
        public int uid { get; set; }
        public string user_name { get; set; }
        public string location { get; set; }
        public string bio { get; set; }
        public string first_name { get; set; }
        public string last_name { get; set; }
        public string user_avatar { get; set; }
        public string account_type { get; set; }
        public object url { get; set; }
    }

    public class User_Beer3
    {
        public int bid { get; set; }
        public string beer_name { get; set; }
        public string beer_label { get; set; }
        public double beer_abv { get; set; }
        public string beer_style { get; set; }
        public string beer_description { get; set; }
        public double auth_rating { get; set; }
        public bool wish_list { get; set; }
    }

    public class User_Contact3
    {
        public string twitter { get; set; }
        public string facebook { get; set; }
        public string instagram { get; set; }
        public string url { get; set; }
    }

    public class User_Location3
    {
        public string brewery_city { get; set; }
        public string brewery_state { get; set; }
        public double lat { get; set; }
        public double lng { get; set; }
    }

    public class User_Brewery3
    {
        public int brewery_id { get; set; }
        public string brewery_name { get; set; }
        public string brewery_slug { get; set; }
        public string brewery_label { get; set; }
        public string country_name { get; set; }
        public User_Contact3 contact { get; set; }
        public User_Location3 location { get; set; }
        public int brewery_active { get; set; }
    }

    public class User_Item5
    {
        public string category_name { get; set; }
        public string category_id { get; set; }
        public bool is_primary { get; set; }
    }

    public class User_Categories
    {
        public int count { get; set; }
        public List<User_Item5> items { get; set; }
    }

    public class User_Location4
    {
        public string venue_address { get; set; }
        public string venue_city { get; set; }
        public string venue_state { get; set; }
        public string venue_country { get; set; }
        public double lat { get; set; }
        public double lng { get; set; }
    }

    public class User_Contact4
    {
        public string twitter { get; set; }
        public string venue_url { get; set; }
    }

    public class User_Foursquare
    {
        public string foursquare_id { get; set; }
        public string foursquare_url { get; set; }
    }

    public class User_VenueIcon
    {
        public string sm { get; set; }
        public string md { get; set; }
        public string lg { get; set; }
    }

    public class User_Venue
    {
        public int venue_id { get; set; }
        public string venue_name { get; set; }
        public string venue_slug { get; set; }
        public string primary_category { get; set; }
        public string parent_category_id { get; set; }
        public User_Categories categories { get; set; }
        public User_Location4 location { get; set; }
        public User_Contact4 contact { get; set; }
        public User_Foursquare foursquare { get; set; }
        public User_VenueIcon venue_icon { get; set; }
        public bool is_verified { get; set; }
    }

    public class User_Item4
    {
        public int photo_id { get; set; }
        public User_Photo photo { get; set; }
        public string created_at { get; set; }
        public int checkin_id { get; set; }
        public User_User4 user { get; set; }
        public User_Beer3 beer { get; set; }
        public User_Brewery3 brewery { get; set; }
        public User_Venue venue { get; set; }
    }



    public class User_Media2
    {
        public int count { get; set; }
        public List<User_Item4> items { get; set; }
    }

    public class User_Badge
    {
        public int badges_to_facebook { get; set; }
        public int badges_to_twitter { get; set; }
    }

    public class User_Checkin
    {
        public int checkin_to_facebook { get; set; }
        public int checkin_to_twitter { get; set; }
        public int checkin_to_foursquare { get; set; }
    }

    public class User_Navigation
    {
        public int default_to_checkin { get; set; }
    }

    public class User_Settings
    {
        public User_Badge badge { get; set; }
        public User_Checkin checkin { get; set; }
        public User_Navigation navigation { get; set; }
        public string email_address { get; set; }
    }

    public class AvailableColor
    {

        public string name { get; set; }

        public string color { get; set; }

        public List<int> values { get; set; }

    }


    public class MainItems
    {
        public string ItemName { get; set; }
        public ObservableCollection<SubItems> SubItemsList { get; set; }
    }

    public class SubItems
    {
        public string SubItemName { get; set; }
    }


    public class IgnoreUnexpectedArraysConverter<T> : IgnoreUnexpectedArraysConverterBase
    {
        public override bool CanConvert(Type objectType)
        {
            return typeof(T).IsAssignableFrom(objectType);
        }
    }

    public class IgnoreUnexpectedArraysConverter : IgnoreUnexpectedArraysConverterBase
    {
        readonly IContractResolver resolver;

        public IgnoreUnexpectedArraysConverter(IContractResolver resolver)
        {
            if (resolver == null)
                throw new ArgumentNullException();
            this.resolver = resolver;
        }

        public override bool CanConvert(Type objectType)
        {
            if (objectType.IsPrimitive || objectType == typeof(string))
                return false;
            return resolver.ResolveContract(objectType) is JsonObjectContract;
        }
    }

    public abstract class IgnoreUnexpectedArraysConverterBase : JsonConverter
    {
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            var contract = serializer.ContractResolver.ResolveContract(objectType);
            if (!(contract is JsonObjectContract))
            {
                throw new JsonSerializationException(string.Format("{0} is not a JSON object", objectType));
            }

            do
            {
                if (reader.TokenType == JsonToken.Null)
                    return null;
                else if (reader.TokenType == JsonToken.Comment)
                    continue;
                else if (reader.TokenType == JsonToken.StartArray)
                {
                    var array = JArray.Load(reader);
                    if (array.Count > 0)
                        throw new JsonSerializationException(string.Format("Array was not empty."));
                    return existingValue ?? contract.DefaultCreator();
                }
                else if (reader.TokenType == JsonToken.StartObject)
                {
                    // Prevent infinite recursion by using Populate()
                    existingValue = existingValue ?? contract.DefaultCreator();
                    serializer.Populate(reader, existingValue);
                    return existingValue;
                }
                else
                {
                    throw new JsonSerializationException(string.Format("Unexpected token {0}", reader.TokenType));
                }
            }
            while (reader.Read());
            throw new JsonSerializationException("Unexpected end of JSON.");
        }

        public override bool CanWrite { get { return false; } }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            throw new NotImplementedException();
        }
    }

    /////  END OF CLASSES /////////

}

谢谢, 瑞克

【问题讨论】:

  • 你能分享你的模型课吗?那么回答你的问题会更容易..
  • 没问题,我刚刚添加了上面的类。

标签: xaml binding uwp


【解决方案1】:

既然你有嵌套,你可以做的是在列表视图中显示checkins.items[],就像你现在显示的那样,一旦用户从签入中选择一个“项目”(即,来自列表视图的项目),在 @列表视图的 987654322@ 或 SelectionChanged 事件获取所选项目并在新的列表视图中显示其“徽章”项目列表。

private void lvRecenCheckins_SelectionChanged(object sender, SelectionChangedEventArgs e)
{ 
    var selectedCheckinItem = (sender as items).badges;
    newListView.ItemSource = selectedCheckinItem.items;
}

请注意:这是基于问题中提供的信息,实际的类名可能不同。

希望这会有所帮助..!如果您有任何疑问,请询问..

【讨论】:

  • 这是一种很好的技术,但在这种情况下,我想在 ListView 中显示与其他数据内联的数据,而不是像主/详细视图那样被点击之后。
【解决方案2】:

也许你可以看看这里:https://docs.microsoft.com/en-us/windows/uwp/xaml-platform/x-bind-markup-extension

我会尝试这样的事情:

<DataTemplate x:DataType="local:YourClass">
    <Grid>
        <TextBlock Text="{x:Bind GetFirstBadgeItemSmall(badges)}" />
    </Grid>
</DataTemplate>

在您的代码中,也就是 ViewModel,您需要实现一个新方法:

public string GetFirstBadgeItemSmall(IEnumerable<badge> badges)
{
    return (badges?.items?[0].badge_image.small ?? string.empty);
}

更新

也许是这样。我没试过,只是猜测:

<DataTemplate>
    <Grid DataContext={Binding badges.items}>
        <TextBlock Text="{Binding badge_image.small}" />
    </Grid>
</DataTemplate>

【讨论】:

  • 我喜欢 x:Bind 但在这种情况下我不能使用它,因为我正在使用设计时数据构建我的 UI,不幸的是 x:Bind 现在不支持。这就是我现在使用 Binding= 的原因。
猜你喜欢
  • 2014-03-12
  • 2011-03-28
  • 1970-01-01
  • 2012-09-08
  • 2020-03-14
  • 1970-01-01
  • 1970-01-01
  • 2014-07-24
  • 1970-01-01
相关资源
最近更新 更多