简体   繁体   English

临时排序WP8列表框

[英]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 ). 我有一个基于本地数据库示例( http://code.msdn.microsoft.com/wpapps/Local-Database-Sample-57b1614c )构建的WP C#应用程序。

The main page displays a list of items from the xml database, which by default shows items in the order created. 主页显示xml数据库中的项目列表,默认情况下按创建的顺序显示项目。 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. 不幸的是,WP不支持Listbox.Sort。

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. 我已经尝试过在这里找到各种答案,包括尝试对xml文件本身进行排序,但是由于超出我的编码水平,它们不会更改列表的顺序(请参阅Templatestorage),但是我怀疑这是由于执行不当所致。

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: C#是:

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: Templatestorage显示了各种排序(注释)尝试:

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(); 无需设置Templates.ItemsSource = storage.GetItems(); in your code, you can keep an ObservableCollection (or other enumerable type) as a class-level variable: 在您的代码中,可以将ObservableCollection(或其他可枚举类型)保留为类级变量:

//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. 然后,您将在XAML中将ItemsSource="{Binding StorageTemplates}"数据绑定应用于您的ListBox。 ( 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. 然后,您可以使用ObservableCollection的内置Sort方法来设置项目的排序顺序。 You may need to implement a Property Changed handler, you can check this tutorial for more information. 您可能需要实现属性更改处理程序,可以查看本教程以获取更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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