【问题标题】:long list selector with json does not working带有 json 的长列表选择器不起作用
【发布时间】:2014-08-29 21:18:35
【问题描述】:

我在使用长列表选择器时遇到问题...我正在通过 json Web 服务填充列表,当设置 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="False" 下正常工作,如果我更改为 true,则列表不会出现。 截图在这里http://social.msdn.microsoft.com/Forums/en-US/b3074356-7924-42b4-bdd0-c2d5a8861d77/longlistselector-not-working-with-isgroupingenabledtrue?forum=wpdevelop&prof=required

【问题讨论】:

    标签: json windows-phone-8 longlistselector


    【解决方案1】:

    似乎问题出在 client_OpenReadCompleted 中。

    在你的代码中有

    this.lbResultado.ItemsSource = wsempresa;
    

    等等。

    而不是你应该设置

    ListaWs = wsempresa;
    SortingListAZ();
    

    【讨论】:

    • 刚刚更改了您提到的行,并在 wsempresa 错误 1 ​​中给出了此错误,无法将类型“System.Collections.ObjectModel.ObservableCollection”隐式转换为“System.Collections。 Generic.List' D:\Projetos WP\PhoneApp4\PhoneApp4\MainPage.xaml.cs 99 23 PhoneApp4还有什么变化吗?
    • 是的,我没有提到这一点。这是因为 ListaWs 不是 observableCollection,尽管 wsempresa 是。我建议您将 ListaWs 类型更改为 observablecollection。另一方面,您可以将 wsempresa 类型更改为 List。
    • 我将 ListaWs 更改为 ObservableCollection 并没有显示更多错误,但是在运行应用程序时没有显示任何内容,列表没有出现并且还显示分组的字母......有什么提示吗?
    • 所以显示字母,但没有项目?我需要json来检查发生了什么。您的代码没有返回任何内容,因此我无法测试该程序。你能描述一个你的json的简短例子吗?然后我可以模拟你的程序。
    • 你要求做的更改只出现一个空白列表,带有 gps 按钮,我在每个列表项中放入...我在此链接上的 json 显示代码 qualamelhormarca.com.br/novapasta/wsempresas.php
    猜你喜欢
    • 1970-01-01
    • 2020-11-04
    • 2016-08-24
    • 2015-03-31
    • 1970-01-01
    • 1970-01-01
    • 2019-06-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多