locked
如何添加ListView的分类选择器? RRS feed

  • 问题

  • 在教程http://msdn.microsoft.com/zh-cn/library/windows/apps/xaml/hh780627.aspx中,有代码:

            protected override GroupStyle SelectGroupStyleCore(object group, uint level)
            {
                return (GroupStyle)App.Current.Resources["listViewGroupStyle"];
            }

    但是运行时报错,说是没有找到资源。我用的是visual studio 2013 ultimate,安装了windows phone sdk,项目是中心应用程序(C#),项目名是“WB实验”。代码:(其他的文件都没有更改)

    HubPage.xaml.cs:

    using WB实验.Common;
    using WB实验.Data;
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Runtime.InteropServices.WindowsRuntime;
    using Windows.ApplicationModel.Resources;
    using Windows.Foundation;
    using Windows.Foundation.Collections;
    using Windows.Graphics.Display;
    using Windows.UI.Core;
    using Windows.UI.ViewManagement;
    using Windows.UI.Xaml;
    using Windows.UI.Xaml.Controls;
    using Windows.UI.Xaml.Controls.Primitives;
    using Windows.UI.Xaml.Data;
    using Windows.UI.Xaml.Input;
    using Windows.UI.Xaml.Media;
    using Windows.UI.Xaml.Media.Imaging;
    using Windows.UI.Xaml.Navigation;
    
    // “中心应用程序”模板在 http://go.microsoft.com/fwlink/?LinkId=391641 上有介绍
    
    namespace WB实验
    {
        /// <summary>
        /// 显示分组的项集合的页。
        /// </summary>
        public sealed partial class HubPage : Page
        {
            private readonly NavigationHelper navigationHelper;
            private readonly ObservableDictionary defaultViewModel = new ObservableDictionary();
            private readonly ResourceLoader resourceLoader = ResourceLoader.GetForCurrentView("Resources");
    
            DateTime startDate;
            public HubPage()
            {
                this.InitializeComponent();
    
                // 仅支持方向为纵向的中心
                DisplayInformation.AutoRotationPreferences = DisplayOrientations.Portrait;
    
                this.NavigationCacheMode = NavigationCacheMode.Required;
    
                this.navigationHelper = new NavigationHelper(this);
                this.navigationHelper.LoadState += this.NavigationHelper_LoadState;
                this.navigationHelper.SaveState += this.NavigationHelper_SaveState;
            }
    
            private void PopulateActivities()
            {
                List<Activity> Activities = new List<Activity>();
    
                Activities.Add(new Activity()
                {
                    Name = "Activity 1",
                    Complete = true,
                    DueDate = startDate.AddDays(4),
                    Project = "Project 1"
                });
                Activities.Add(new Activity()
                {
                    Name = "Activity 2",
                    Complete = true,
                    DueDate = startDate.AddDays(5),
                    Project = "Project 1"
                });
                Activities.Add(new Activity()
                {
                    Name = "Activity 3",
                    Complete = false,
                    DueDate = startDate.AddDays(7),
                    Project = "Project 1"
                });
                Activities.Add(new Activity()
                {
                    Name = "Activity 4",
                    Complete = false,
                    DueDate = startDate.AddDays(9),
                    Project = "Project 1"
                });
                Activities.Add(new Activity()
                {
                    Name = "Activity 5",
                    Complete = false,
                    DueDate = startDate.AddDays(14),
                    Project = "Project 1"
                });
                Activities.Add(new Activity()
                {
                    Name = "Activity A",
                    Complete = true,
                    DueDate = startDate.AddDays(2),
                    Project = "Project 2"
                });
                Activities.Add(new Activity()
                {
                    Name = "Activity B",
                    Complete = false,
                    DueDate = startDate.AddDays(4),
                    Project = "Project 2"
                });
                Activities.Add(new Activity()
                {
                    Name = "Activity C",
                    Complete = true,
                    DueDate = startDate.AddDays(5),
                    Project = "Project 2"
                });
                Activities.Add(new Activity()
                {
                    Name = "Activity D",
                    Complete = false,
                    DueDate = startDate.AddDays(9),
                    Project = "Project 2"
                });
                Activities.Add(new Activity()
                {
                    Name = "Activity E",
                    Complete = false,
                    DueDate = startDate.AddDays(18),
                    Project = "Project 2"
                });
    
                var result = from act in Activities group act by act.Project into grp orderby grp.Key select grp;
                cvsActivities.Source = result;
            }
    
            private void PopulateProjects()
            {
                List<Project> Projects = new List<Project>();
    
                Project newProject = new Project();
                newProject.Name = "Project 1";
                newProject.Activities.Add(new Activity() { Name = "Activity 1", Complete = true, DueDate = startDate.AddDays(4) });
                newProject.Activities.Add(new Activity() { Name = "Activity 2", Complete = true, DueDate = startDate.AddDays(5) });
                newProject.Activities.Add(new Activity() { Name = "Activity 3", Complete = false, DueDate = startDate.AddDays(7) });
                newProject.Activities.Add(new Activity() { Name = "Activity 4", Complete = false, DueDate = startDate.AddDays(9) });
                newProject.Activities.Add(new Activity() { Name = "Activity 5", Complete = false, DueDate = startDate.AddDays(14) });
                Projects.Add(newProject);
    
                newProject = new Project();
                newProject.Name = "Project 2";
                newProject.Activities.Add(new Activity() { Name = "Activity A", Complete = true, DueDate = startDate.AddDays(2) });
                newProject.Activities.Add(new Activity() { Name = "Activity B", Complete = false, DueDate = startDate.AddDays(3) });
                newProject.Activities.Add(new Activity() { Name = "Activity C", Complete = true, DueDate = startDate.AddDays(5) });
                newProject.Activities.Add(new Activity() { Name = "Activity D", Complete = false, DueDate = startDate.AddDays(9) });
                newProject.Activities.Add(new Activity() { Name = "Activity E", Complete = false, DueDate = startDate.AddDays(18) });
                Projects.Add(newProject);
    
                newProject = new Project();
                newProject.Name = "Project 3";
                Projects.Add(newProject);
    
                cvsProjects.Source = Projects;
            }
    
            public NavigationHelper NavigationHelper
            {
                get { return this.navigationHelper; }
            }
    
            public ObservableDictionary DefaultViewModel
            {
                get { return this.defaultViewModel; }
            }
    
    
            private async void NavigationHelper_LoadState(object sender, LoadStateEventArgs e)
            {
                // TODO:  创建适用于问题域的合适数据模型以替换示例数据
                var sampleDataGroups = await SampleDataSource.GetGroupsAsync();
                this.DefaultViewModel["Groups"] = sampleDataGroups;
            }
    
            private void NavigationHelper_SaveState(object sender, SaveStateEventArgs e)
            {
            }
            private void GroupSection_ItemClick(object sender, ItemClickEventArgs e)
            {
                var groupId = ((SampleDataGroup)e.ClickedItem).UniqueId;
                if (!Frame.Navigate(typeof(SectionPage), groupId))
                {
                    throw new Exception(this.resourceLoader.GetString("NavigationFailedExceptionMessage"));
                }
            }
    
            private void ItemView_ItemClick(object sender, ItemClickEventArgs e)
            {
                // 导航至相应的目标页,并
                // 通过将所需信息作为导航参数传入来配置新页
                var a = e.ClickedItem;
                var b=(SampleDataItem)a;
                var c = b.UniqueId;
                var itemId = ((SampleDataItem)e.ClickedItem).UniqueId;
                if (!Frame.Navigate(typeof(ItemPage), itemId))
                {
                    throw new Exception(this.resourceLoader.GetString("NavigationFailedExceptionMessage"));
                }
            }
    
            #region NavigationHelper 注册
            protected override void OnNavigatedTo(NavigationEventArgs e)
            {
                this.navigationHelper.OnNavigatedTo(e);
    
                DateTime.TryParse("1/1/2014",out startDate);
    
                PopulateProjects();
                PopulateActivities();
            }
    
            protected override void OnNavigatedFrom(NavigationEventArgs e)
            {
                this.navigationHelper.OnNavigatedFrom(e);
            }
    
            #endregion
        }
        public class ListGroupStyleSelector : GroupStyleSelector
        {
            protected override GroupStyle SelectGroupStyleCore(object group, uint level)
            {
                return (GroupStyle)App.Current.Resources["listViewGroupStyle"];
            }
        }
        public class Project
        {
            public Project()
            {
                Activities = new System.Collections.ObjectModel.ObservableCollection<Activity>();
            }
    
            public string Name { get; set; }
            public System.Collections.ObjectModel.ObservableCollection<Activity> Activities { get; private set; }
        }
        public class Activity
        {
            public string Name { get; set; }
            public DateTime DueDate { get; set; }
            public bool Complete { get; set; }
            public string Project { get; set; }
        }
    }

    HubPage.xaml:

    <Page
        x:Class="WB实验.HubPage"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="using:WB实验"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:data="using:WB实验.Data"
        DataContext="{Binding DefaultViewModel, RelativeSource={RelativeSource Self}}"
        d:DataContext="{Binding Source={d:DesignData Source=/DataModel/SampleData.json, Type=data:SampleDataSource}}"
        mc:Ignorable="d">
    
        <Page.Resources>
            <CollectionViewSource x:Name="cvsActivities" IsSourceGrouped="True"/>
    
            <CollectionViewSource x:Name="cvsProjects" IsSourceGrouped="True" ItemsPath="Activities"/>
    
            <local:ListGroupStyleSelector x:Key="listGroupStyleSelector"/>
            
    
            <DataTemplate x:Key="HubSectionHeaderTemplate">
                <TextBlock Margin="0,0,0,-9.5" Text="{Binding}"/>
            </DataTemplate>
    
            <!-- 适合网格的项模板,如第 2 部分中所示 -->
            <DataTemplate x:Key="Standard200x180TileItemTemplate">
                <Grid Margin="0,0,9.5,9.5" Background="{ThemeResource ListViewItemPlaceholderBackgroundThemeBrush}">
                    <Image Source="{Binding ImagePath}" Stretch="UniformToFill" AutomationProperties.Name="{Binding Title}" Height="138.5" Width="138.5"/>
                    <TextBlock Text="{Binding Title}" VerticalAlignment="Bottom" Margin="9.5,0,0,6.5" Style="{ThemeResource BaseTextBlockStyle}"/>
                </Grid>
            </DataTemplate>
    
            <DataTemplate x:Key="StandardTripleLineItemTemplate">
                <Grid>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="Auto"/>
                        <ColumnDefinition Width="*"/>
                    </Grid.ColumnDefinitions>
    
                    <Border Background="{ThemeResource ListViewItemPlaceholderBackgroundThemeBrush}" Margin="0,9.5,0,0" Grid.Column="0" HorizontalAlignment="Left">
                        <Image Source="{Binding ImagePath}" Stretch="UniformToFill" AutomationProperties.Name="{Binding Title}" Height="79" Width="79"/>
                    </Border>
                    <StackPanel Grid.Column="1" Margin="14.5,0,0,0">
                        <TextBlock Text="{Binding Title}" Style="{ThemeResource ListViewItemTextBlockStyle}"/>
                        <TextBlock Text="{Binding Description}" Style="{ThemeResource ListViewItemContentTextBlockStyle}" Foreground="{ThemeResource PhoneMidBrush}" />
                        <TextBlock Text="{Binding Subtitle}" Style="{ThemeResource ListViewItemSubheaderTextBlockStyle}" />
                    </StackPanel>
                </Grid>
            </DataTemplate>
    
            <DataTemplate x:Key="StandardDoubleLineItemTemplate">
                <Grid>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="Auto"/>
                        <ColumnDefinition Width="*"/>
                    </Grid.ColumnDefinitions>
    
                    <Border Background="{ThemeResource ListViewItemPlaceholderBackgroundThemeBrush}" Margin="0,9.5,0,0" Grid.Column="0" HorizontalAlignment="Left">
                        <Image Source="{Binding ImagePath}" Stretch="UniformToFill" AutomationProperties.Name="{Binding Title}" Height="79" Width="79"/>
                    </Border>
                    <StackPanel Grid.Column="1" Margin="14.5,0,0,0">
                        <TextBlock Text="{Binding Title}" Style="{ThemeResource ListViewItemTextBlockStyle}"/>
                        <TextBlock Text="{Binding Subtitle}" Style="{ThemeResource ListViewItemSubheaderTextBlockStyle}"/>
                    </StackPanel>
                </Grid>
            </DataTemplate>
        </Page.Resources>
    
        <Grid x:Name="LayoutRoot">
            <Hub x:Name="Hub" x:Uid="Hub" Header="application name" Background="{ThemeResource HubBackgroundImageBrush}">
                <HubSection x:Uid="HubSection1" Header="SECTION 1" DataContext="{Binding Groups}" HeaderTemplate="{ThemeResource HubSectionHeaderTemplate}">
                    <DataTemplate>
                        <ListView
                            ItemsSource="{Binding}"
                            IsItemClickEnabled="True"
                            ItemClick="GroupSection_ItemClick"
                            ContinuumNavigationTransitionInfo.ExitElementContainer="True">
                            <ListView.ItemTemplate>
                                <DataTemplate>
                                    <StackPanel Margin="0,0,0,27.5">
                                        <TextBlock Text="{Binding Title}" Style="{ThemeResource ListViewItemTextBlockStyle}" />
                                    </StackPanel>
                                </DataTemplate>
                            </ListView.ItemTemplate>
                        </ListView>
                    </DataTemplate>
                </HubSection>
    
                <HubSection x:Uid="HubSection2" Header="SECTION 2" Width="Auto"
                             DataContext="{Binding Groups[0]}" HeaderTemplate="{ThemeResource HubSectionHeaderTemplate}">
                    <DataTemplate>
                        <GridView
                            Margin="0,9.5,0,0"
                            ItemsSource="{Binding Items}"
                            AutomationProperties.AutomationId="ItemGridView"
                            AutomationProperties.Name="Items In Group"
                            ItemTemplate="{StaticResource Standard200x180TileItemTemplate}"
                            SelectionMode="None"
                            IsItemClickEnabled="True"
                            ItemClick="ItemView_ItemClick"
                            ContinuumNavigationTransitionInfo.ExitElementContainer="True">
                            <GridView.ItemsPanel>
                                <ItemsPanelTemplate>
                                    <ItemsWrapGrid />
                                </ItemsPanelTemplate>
                            </GridView.ItemsPanel>
                        </GridView>
                    </DataTemplate>
                </HubSection>
    
                <HubSection x:Uid="HubSection3" Header="SECTION 3"
                            DataContext="{Binding Groups[1]}" HeaderTemplate="{ThemeResource HubSectionHeaderTemplate}">
                    <DataTemplate>
                        <ListView 
                            AutomationProperties.AutomationId="ItemListViewSection3"
                            AutomationProperties.Name="Items In Group"
                            SelectionMode="None"
                            IsItemClickEnabled="True"
                            ItemsSource="{Binding Items}"
                            ItemTemplate="{StaticResource StandardTripleLineItemTemplate}"
                            ItemClick="ItemView_ItemClick"
                            ContinuumNavigationTransitionInfo.ExitElementContainer="True">
                        </ListView>
                    </DataTemplate>
                </HubSection>
    
                <HubSection x:Uid="HubSection4" Header="SECTION 4"
                            DataContext="{Binding Groups[2]}" HeaderTemplate="{ThemeResource HubSectionHeaderTemplate}">
                    <DataTemplate>
                        <ListView 
                            AutomationProperties.AutomationId="ItemListViewSection4"
                            AutomationProperties.Name="Items In Group"
                            SelectionMode="None"
                            IsItemClickEnabled="True"
                            ItemsSource="{Binding Items}"
                            ItemClick="ItemView_ItemClick"
                            ContinuumNavigationTransitionInfo.ExitElementContainer="True"
                            GroupStyleSelector="{StaticResource listGroupStyleSelector}">
                            <ListView.ItemTemplate>
                                <DataTemplate>
                                    <StackPanel Margin="0,0,0,19">
                                        <TextBlock Text="{Binding Title}" Style="{ThemeResource ListViewItemTextBlockStyle}"/>
                                        <TextBlock Text="{Binding Subtitle}" Style="{ThemeResource ListViewItemSubheaderTextBlockStyle}"/>
                                    </StackPanel>
                                </DataTemplate>
                            </ListView.ItemTemplate>
                        </ListView>
                    </DataTemplate>
                </HubSection>
    
                <HubSection x:Uid="HubSection5" Header="SECTION 5"
                            DataContext="{Binding Groups[3]}" HeaderTemplate="{ThemeResource HubSectionHeaderTemplate}">
                    <DataTemplate>
                        <ListView 
                            AutomationProperties.AutomationId="ItemListViewSection5"
                            AutomationProperties.Name="Items In Group"
                            SelectionMode="None"
                            IsItemClickEnabled="True"
                            ItemsSource="{Binding Items}"
                            ItemTemplate="{StaticResource StandardDoubleLineItemTemplate}"
                            ItemClick="ItemView_ItemClick"
                            ContinuumNavigationTransitionInfo.ExitElementContainer="True">
                        </ListView>
                    </DataTemplate>
                </HubSection>
    
                <HubSection x:Uid="HubSection6" Header="NEW1 类似4">
                    <DataTemplate>
                        <ListView 
                            AutomationProperties.AutomationId="NEW1_"
                            AutomationProperties.Name="Items In Groupes"
                            SelectionMode="None"
                            IsItemClickEnabled="True"
                            ItemsSource="{Binding Source={StaticResource cvsActivities}}"
                            ItemClick="ItemView_ItemClick"
                            ContinuumNavigationTransitionInfo.ExitElementContainer="True"
                            
                            >
                            <ListView.GroupStyle>
                                
                            </ListView.GroupStyle>
                            <ListView.ItemTemplate>
                                <DataTemplate>
                                    <StackPanel Margin="0,0,0,19">
                                        <TextBlock Text="{Binding Name}" Style="{ThemeResource ListViewItemTextBlockStyle}"/>
                                        <TextBlock Text="{Binding Project}" Style="{ThemeResource ListViewItemSubheaderTextBlockStyle}"/>
                                        <TextBlock Text="{Binding Duedate}"/>
                                    </StackPanel>
                                </DataTemplate>
                            </ListView.ItemTemplate>
                        </ListView>
                    </DataTemplate>
                </HubSection>
            </Hub>
        </Grid>
    </Page>
    怎么办?


    2014年8月11日 6:45

答案

全部回复