简体   繁体   中英

Temporarily Sort WP8 Listbox

I have an WP C# app built on the Local Database Sample ( http://code.msdn.microsoft.com/wpapps/Local-Database-Sample-57b1614c ).

The main page displays a list of items from the xml database, which by default shows items in the order created. I would like to be able to offer at least one other sort order - either reversed or sorted by "Subject". Unfortunately Listbox.Sort is not supported in WP.

I have tried various answers found on here, including attempting to sort the xml file itself, but for reasons beyond my level of coding they do not change the order of the list (see Templatestorage) however i suspect it is due to improper implementation.

The code for the listbox is:

<ListBox x:Name="Templates" SelectionChanged="OnSelectionChanged" Background="Transparent" Style="{StaticResource ListBoxStyle1}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel>
        <TextBlock Grid.Row="2" Text="{Binding Subject}" Style="{StaticResource PhoneTextLargeStyle}" Margin="12,2" />
        <TextBlock Grid.Row="2" Text="{Binding DT}" Style="{StaticResource PhoneTextSmallStyle}" Margin="12,5" />
                <Rectangle Height="1" Margin="23,7,50,7" Fill="{StaticResource PhoneAccentBrush}" MinWidth="400" />
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

The c# is:

public partial class MainPage
{
    private readonly TemplateStorage storage = new TemplateStorage();

    public MainPage()
    {

        InitializeComponent();

        Loaded += OnLoaded;
    }

    private void OnLoaded(object sender, RoutedEventArgs e)
    {

        Templates.ItemsSource = storage.GetItems();
        this.NavigationService.RemoveBackEntry();
    }

    private void PhoneApplicationPage_GotFocus(object sender, RoutedEventArgs e)
    {
        Templates.ItemsSource = storage.GetItems();            
    }
}

The Templatestorage, which shows the various attempts at sorting (commented out) is:

public class TemplateStorage
{
    private IList<NanoMemoTemplate> templates;
    private const string Filename = "template-list.xml";

    protected IList<NanoMemoTemplate> Templates
    {
        get
        {
            return templates ?? (templates = LoadTemplates().ToList());
        }
        set
        {
            templates = value;
        }
    }


    protected IEnumerable<NanoMemoTemplate> LoadTemplates()
    {
        using(var applicationStorage = IsolatedStorageFile.GetUserStoreForApplication())
        {
            if(!applicationStorage.FileExists(Filename))
                return Enumerable.Empty<NanoMemoTemplate>();



            using(var speedListFile = applicationStorage.OpenFile(Filename, FileMode.Open, FileAccess.Read))
            {
                var document = XDocument.Load(speedListFile);

                return from t in document.Root.Elements("template")
                        select new NanoMemoTemplate
                        {
                            Id = new Guid(t.Attribute("id").Value),
                            Subject = t.Attribute("subject").Value,
                            Body = t.Attribute("body").Value,
                            DT = t.Attribute("dateCreated").Value,
                        };
            }
        }
    }

    //public IEnumerable<NanoMemoTemplate> SortTemplates()
    //{

    //    using (var applicationStorage = IsolatedStorageFile.GetUserStoreForApplication())
    //    {
    //        if (!applicationStorage.FileExists(Filename))
    //            return Enumerable.Empty<NanoMemoTemplate>();

    //        using (var speedListFile = applicationStorage.OpenFile(Filename, FileMode.Open, FileAccess.ReadWrite))
    //        {
    //            var documentSort = XDocument.Load(speedListFile);
    //            XDocument datatemp = new XDocument(documentSort);
    //            var subjectSort = from p in datatemp.Descendants("template")
    //                              orderby (string)p.Attribute("subject")
    //                              select p;
    //            //var subjectSort = datatemp.Elements("template").OrderBy(p => (string)p.Attribute("subject")).ToArray();
    //            string cleanDataDump = subjectSort.ToString();
    //            MessageBox.Show(cleanDataDump);
    //            documentSort.Descendants("template").Remove();
    //            documentSort.Element("template").Add(subjectSort);

    //            return Templates;
    //        }

    //    }


    //}

    //public IEnumerable<NanoMemoTemplate> SortItems()
    //{

    //    //Sort XML order so order is saved
    //    using (var applicationStorage = IsolatedStorageFile.GetUserStoreForApplication())
    //    {
    //        if (!applicationStorage.FileExists(Filename))
    //            return Enumerable.Empty<NanoMemoTemplate>();

    //        using (var speedListFile = applicationStorage.OpenFile(Filename, FileMode.Open, FileAccess.ReadWrite))
    //        {
    //            var documentSort = XDocument.Load(speedListFile);
    //            IEnumerable<string> codes = from code in documentSort.Elements("template")
    //                                        let subs = (string)code.Element("subject")
    //                                        orderby subs
    //                                        select subs;

    //            //return Templates as per usual as sorting is done at DB level
    //            return from t in documentSort.Root.Elements("template")
    //                   select new NanoMemoTemplate
    //                   {
    //                       Id = new Guid(t.Attribute("id").Value),
    //                       Subject = t.Attribute("subject").Value,
    //                       Body = t.Attribute("body").Value,
    //                       DT = t.Attribute("dateCreated").Value,
    //                   };


    //        }
    //    }
    //}



    public IEnumerable<NanoMemoTemplate> GetItems()
    {
        return Templates;
    }

    public void Save(NanoMemoTemplate template)
    {
        Templates.Add(template);
    }

    public void Delete(NanoMemoTemplate template)
    {
        Templates.Remove(template);
    }

    //public void Sort(NanoMemoTemplate template)
    //{
    //    IList<NanoMemoTemplate> list = new List<NanoMemoTemplate>();
    //    IEnumerable<NanoMemoTemplate> sortedEnum = list.OrderBy(Templates => Templates.Subject);
    //    IList<NanoMemoTemplate> sortedList = sortedEnum.ToList();
    //}

    public void SaveChanges()
    {
        using(var applicationStorage = IsolatedStorageFile.GetUserStoreForApplication())
        using(var speedListFile = applicationStorage.OpenFile(Filename, FileMode.Create, FileAccess.Write))
        {
            var document = new XDocument(new XDeclaration("1.0", "utf-8", "yes"),
                new XElement("templates",
                    from t in Templates
                    select new XElement("template",
                        new XAttribute("id", t.Id),
                        new XAttribute("subject", t.Subject),
                        new XAttribute("body", t.Body),
                        new XAttribute("dateCreated", t.DT))));

            document.Save(speedListFile);
        }
    }
}

Instead of having to set Templates.ItemsSource = storage.GetItems(); in your code, you can keep an ObservableCollection (or other enumerable type) as a class-level variable:

//StorageTemplates should be a class-level variable
ObservableCollection<NanoMemoTemplate> StorageTemplates;

//You can assign the value to StorageTemplates when the page loads
StorageTemplates = storage.GetItems();

You would then apply an ItemsSource="{Binding StorageTemplates}" data binding to your ListBox in XAML. ( See this for more info on binding)

<ListBox x:Name="Templates" ItemsSource="{Binding StorageTemplates, UpdateSourceTrigger="PropertyChanged"}" SelectionChanged="OnSelectionChanged" Background="Transparent" Style="{StaticResource ListBoxStyle1}" >
    <ListBox.ItemTemplate>
        ....
    </ListBox.ItemTemplate>
</ListBox>

Then you can use the built-in Sort methods of the ObservableCollection to set your sort order for the items. You may need to implement a Property Changed handler, you can check this tutorial for more information.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM