使用json的长列表选择器不起作用

时间:2014-07-09 00:30:58

标签: json windows-phone-8 longlistselector

我有一个长列表选择器的问题...我正在通过json webservice填充列表,当一个集合IsGroupingEnabled =" true"列表没有显示...如果我改为IsGroupingEnabled =" false"列表显示正确但不会出现分组的字母......

这是我的代码

XAML

<phone:PhoneApplicationPage
x:Class="PhoneApp4.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d" d:DesignWidth="480" d:DesignHeight="768"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"

SupportedOrientations="Portrait" Orientation="Portrait"
shell:SystemTray.IsVisible="True">
<phone:PhoneApplicationPage.Resources>
    <DataTemplate x:Key="ListTemplate">
        <StackPanel VerticalAlignment="Top" Orientation="Horizontal">
            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="Auto" />
                    <ColumnDefinition Width="300" />
                </Grid.ColumnDefinitions>
                <Grid.RowDefinitions>
                    <RowDefinition Height="Auto"/>
                    <RowDefinition Height="Auto"/>
                </Grid.RowDefinitions>
                <Image Width="150" 
                           Height="150" 
                           Grid.RowSpan="2"
                           Grid.Column="0" 
                           Source="{Binding foto1}"
                           Margin="10" 
                           VerticalAlignment="Top">
                </Image>

                <TextBlock FontWeight="Bold" 
                               Foreground="{StaticResource PhoneAccentBrush}" 
                               FontSize="20" 
                               Text="{Binding nome}" 
                               Grid.Row="1" 
                               Grid.Column="1" 
                               TextWrapping="Wrap" />

                <Button x:Name="gps" 
                            Grid.Row="1" 
                            Grid.Column="2" 
                            Height="75" 
                            Content="GPS" 
                            Click="gps_Click"
                            Margin="90"/>
            </Grid>
        </StackPanel>
    </DataTemplate>

    <DataTemplate x:Key="ListGroupHeaderTemplate">
        <Border  Padding="5">
            <Border  BorderBrush="{StaticResource PhoneAccentBrush}" BorderThickness="2" Width="62" 
     Height="62" Margin="0,0,18,0" HorizontalAlignment="Left">
                <TextBlock Text="{Binding Key}" Foreground="{StaticResource PhoneForegroundBrush}" FontSize="48" Padding="6" 
        FontFamily="{StaticResource PhoneFontFamilySemiLight}" HorizontalAlignment="Left" VerticalAlignment="Center"/>
            </Border>
        </Border>
    </DataTemplate>

    <phone:JumpListItemBackgroundConverter x:Key="BackgroundConverter"/>
    <phone:JumpListItemForegroundConverter x:Key="ForegroundConverter"/>
    <Style x:Key="ListJumpListStyle" TargetType="phone:LongListSelector">
        <Setter Property="GridCellSize"  Value="113,113"/>
        <Setter Property="LayoutMode" Value="Grid" />
        <Setter Property="ItemTemplate">
            <Setter.Value>
                <DataTemplate>
                    <Border  Width="113" Height="113" Margin="6" >
                        <TextBlock Text="{Binding Key}" FontFamily="{StaticResource PhoneFontFamilySemiBold}" FontSize="48" Padding="6" 
           Foreground="{Binding Converter={StaticResource ForegroundConverter}}" VerticalAlignment="Center"/>
                    </Border>
                </DataTemplate>
            </Setter.Value>
        </Setter>
    </Style>

</phone:PhoneApplicationPage.Resources>

<!--LayoutRoot is the root grid where all page content is placed-->
<Grid x:Name="LayoutRoot">
    <Grid.RowDefinitions>
        <RowDefinition Height="80"/>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>

    <!--header-->
    <StackPanel Grid.Row="0" Background="Red" Orientation="Horizontal">
        <TextBlock Text="Teste" Margin="0,0,0,0" VerticalAlignment="Center" FontFamily="Segoe WP SemiLight" FontSize="36"/>
    </StackPanel>

    <!--LongListSelecttor binding with friends informations-->

    <Grid x:Name="ContentPanel" Grid.Row="1" Margin="5,0,0,0">
        <phone:LongListSelector
            ItemsSource="{Binding listaws}"
              x:Name="lbResultado"
              JumpListStyle="{StaticResource ListJumpListStyle}"
              GroupHeaderTemplate="{StaticResource ListGroupHeaderTemplate}"
              ItemTemplate="{StaticResource ListTemplate}"
              LayoutMode="List"
              IsGroupingEnabled="True"                
              HideEmptyGroups ="False" 
            />
    </Grid>
</Grid>

MAINPAGE.XAML.C $

using Microsoft.Phone.Controls;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Net;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;
using PhoneApp4;
using System.Threading;
using Newtonsoft.Json;


namespace PhoneApp4
{
    public partial class MainPage : PhoneApplicationPage
    {

        List<Wsempresa> ListaWs = new List<Wsempresa>();
        private const string DRIVING_PROTOCOL = "ms-drive-to";
        // Constructor
        public MainPage()
        {
            InitializeComponent();
           // myButton.Click += new RoutedEventHandler(myButton_Click);
            SortingListAZ();
            string URL = "http://qualamelhormarca.com.br/novapasta/wsempresas.php";
            this.Loaded += MainPage_Loaded;
            WebClient client = new WebClient();
            client.OpenReadCompleted += new OpenReadCompletedEventHandler(client_OpenReadCompleted);
            client.OpenReadAsync(new Uri(URL, UriKind.Absolute));

            //LayoutRoot.Opacity = 0.5;
            lbResultado.IsEnabled = false;
        }

        private void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            //List<Wsempresa> listaws = new List<Wsempresa>();
            //List<AlphaKeyGroup<Wsempresa>> list = AlphaKeyGroup<Wsempresa>.CreateGroups(listaws, Thread.CurrentThread.CurrentUICulture, c => c.nome, true);
            //lbResultado.ItemsSource = list; 
        }
        //void myButton_Click(object sender, RoutedEventArgs e)
        //{
        //    string URL = "http://192.168.1.4/QualAMelhorMarca/Divulguefranca/controller/wsempresas.php";

        //    WebClient client = new WebClient();
        //    client.OpenReadCompleted += new OpenReadCompletedEventHandler(client_OpenReadCompleted);
        //    client.OpenReadAsync(new Uri(URL, UriKind.Absolute));

        //    LayoutRoot.Opacity = 0.5;
        //    lbResultado.IsEnabled = false;

        //   // busca.Visibility = System.Windows.Visibility.Visible;
        //    myButton.Visibility = System.Windows.Visibility.Collapsed;
        //    //txtbusca.Visibility = System.Windows.Visibility.Visible;
        //    // pesquisar.Visibility = System.Windows.Visibility.Visible;



        //}
        private void SortingListAZ()
        {
            List<AlphaKeyGroup<Wsempresa>> DataSource = AlphaKeyGroup<Wsempresa>.CreateGroups(ListaWs,
                System.Threading.Thread.CurrentThread.CurrentUICulture,
                (Wsempresa s) => { return s.nome; }, true);

            lbResultado.ItemsSource = DataSource;

        }
        void client_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
        {
            DataContractJsonSerializer json =
                new DataContractJsonSerializer(typeof(Wsempresa));
            Wsempresa lista = (Wsempresa)json.ReadObject(e.Result);

            ObservableCollection<Wsempresa> wsempresa = new ObservableCollection<Wsempresa>();
            try
            {
                // var root = JsonConvert.DeserializeObject<Wsempresa>(e.Result);
                Wsempresa root = (Wsempresa)json.ReadObject(e.Result);
                if (wsempresa.Count != 0)
                {
                    wsempresa.Clear();
                }
                foreach (Wsempresa wsempresas in root.wsempresas)
                {
                    Wsempresa list = wsempresas;
                    wsempresa.Add(list);
                }
            }
            catch (Exception ex)
            {
            }
            this.lbResultado.ItemsSource = wsempresa;
           // lbResultado.ItemsSource = wsempresa;
           // lbResultado.ItemsSource = lista.wsempresas;

          //  LayoutRoot.Opacity = 1;
            lbResultado.IsEnabled = true;
        }
            [DataContract(Name = "wsempresa")]
        public class Wsempresa
        {
            [DataMember(Name = "nome")]
            public string nome { get; set; }
                [DataMember(Name = "foto1")]
            public string foto1 { get; set; }
                [DataMember(Name = "telefone_comercial")]
            public string telefone_comercial { get; set; }
                [DataMember(Name = "latitude")]
            public string latitude { get; set; }
                [DataMember(Name = "longitude")]
            public string longitude { get; set; }

                [DataMember(Name = "wsempresas")]
                public Wsempresa[] wsempresas { get; set; }
        }

        public class RootObject
        {
            public List<Wsempresa> wsempresas { get; set; }
        }



        void gps_Click(object sender, RoutedEventArgs e)
        {
            Wsempresa wsempresa = (Wsempresa)((Button)sender).DataContext;
            string latitude = wsempresa.latitude;
            string longitude = wsempresa.longitude;
            string nome = wsempresa.nome;


            string uriProtocol = null;
            string uri;

            // Driving or walking directions?
            string buttonClicked = ((Button)sender).Name;
            switch (buttonClicked)
            {
                case "gps":
                    uriProtocol = DRIVING_PROTOCOL;
                    break;
                default:
                    uriProtocol = DRIVING_PROTOCOL;
                    break;
            }

            // Assemble the Uri for the request.
            uri = uriProtocol + ":?" +
                "destination.latitude=" + latitude + "&" +
                "destination.longitude=" + longitude + "&" +
                "destination.name=" + nome;


            // Make the request.
            RequestDirections(uri);
        }

        async void RequestDirections(string uri)
        {
            // Make the request.
            var success = await Windows.System.Launcher.LaunchUriAsync(new Uri(uri));
            if (success)
            {
                // Request succeeded.
            }
            else
            {
                // Request failed.
            }
        }



    }

}

AlphaKeyGroup.c $

   using Microsoft.Phone.Globalization;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PhoneApp4
{
    public class AlphaKeyGroup<T> : List<T>
    {
        /// <summary>
        /// O delegate que é usado para obter a informação da chave
        /// </summary>
        /// <param name="item">Um objeto do tipo T</param>
        /// <returns>O valor da chave usado para esse objeto</returns>
        public delegate string GetKeyDelegate(T item);

        /// <summary>
        /// A chave deste grupo
        /// </summary>
        public string Key { get; private set; }

        /// <summary>
        /// Construtor público
        /// </summary>
        /// <param name="key"></param>
        public AlphaKeyGroup(string key)
        {
            Key = key;

        }

        /// <summary>
        /// Cria uma lista de AlphaKeyGroup<T> com chaves "setadas" por um SortedLocaleGrouping
        /// </summary>
        /// <param name="slg"></param>
        /// <returns>Fonte de dados para o LongListSelector</returns>
        private static List<AlphaKeyGroup<T>> CreateGroups(SortedLocaleGrouping slg)
        {
            List<AlphaKeyGroup<T>> list = new List<AlphaKeyGroup<T>>();

            foreach (string key in slg.GroupDisplayNames)
            {
                list.Add(new AlphaKeyGroup<T>(key));
            }

            return list;
        }

        /// <summary>
        /// Cria uma lista de AlphaGroup<T> com as chaves "setadas" por um SortedLocaleGrouping
        /// </summary>
        /// <param name="items">Os itens a serem colocados em grupo</param>
        /// <param name="ci">A CultureInfo para ordenar e agrupar</param>
        /// <param name="getKey">Um delegate para pegar a chave de um item</param>
        /// <param name="sort">Irá ordenar os dados se for "true"</param>
        /// <returns>Uma fonte de dados para o LongListSelector</returns>
        public static List<AlphaKeyGroup<T>> CreateGroups(IEnumerable<T> items, CultureInfo ci, GetKeyDelegate getKey, bool sort)
        {
            SortedLocaleGrouping slg = new SortedLocaleGrouping(ci);
            List<AlphaKeyGroup<T>> list = CreateGroups(slg);

            foreach (T item in items)
            {
                int index = 0;
                if (slg.SupportsPhonetics)
                {
                    //index = slg.GetGroupIndex(getKey(Yomiof(item)));
                }
                else
                {
                    index = slg.GetGroupIndex(getKey(item));
                }
                if (index >= 0 && index < list.Count)
                {
                    list[index].Add(item);
                }
            }
            if (sort)
            {
                foreach (AlphaKeyGroup<T> group in list)
                {
                    group.Sort((c0, c1) => { return ci.CompareInfo.Compare(getKey(c0), getKey(c1)); });
                }
            }
            return list;
        }
    }
}

注意:我在msdn论坛上提出了这个问题,答案是我的json没有从你的JSON调用中返回数据。 但是我发送了一些我的手机屏幕,显示我的json正在使用IsGroupingEnabled =&#34; False&#34 ;,如果我改为true,列表不会出现。  sreenshot在这里http://social.msdn.microsoft.com/Forums/en-US/b3074356-7924-42b4-bdd0-c2d5a8861d77/longlistselector-not-working-with-isgroupingenabledtrue?forum=wpdevelop&prof=required

1 个答案:

答案 0 :(得分:0)

似乎问题在于client_OpenReadCompleted。

在您的代码中有

this.lbResultado.ItemsSource = wsempresa;

等等。

而不是你应该设置

ListaWs = wsempresa;
SortingListAZ();