背水一戰 Windows 10 (51) - 控件(集合類): ItemsControl - 項模板選擇器, 數據分組


[源碼下載]


背水一戰 Windows 10 (51) - 控件(集合類): ItemsControl - 項模板選擇器, 數據分組



作者:webabcd


介紹
背水一戰 Windows 10 之 控件(集合類 - ItemsControl)

  • 項模板選擇器
  • 數據分組



示例
1、ItemsControl 的項模板選擇器
Controls/CollectionControl/ItemsControlDemo/ItemsControlDemo3.xaml

<Page
    x:Class="Windows10.Controls.CollectionControl.ItemsControlDemo.ItemsControlDemo3"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:Windows10.Controls.CollectionControl.ItemsControlDemo"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    
    xmlns:common="using:Windows10.Common">

    <Page.Resources>
        <!--
            DataTemplate - 數據模板
        -->
        <DataTemplate x:DataType="common:Employee" x:Key="DataTemplateMale">
            <Grid Background="Blue">
                <TextBlock Text="{x:Bind Name}" />
            </Grid>
        </DataTemplate>
        <DataTemplate x:DataType="common:Employee" x:Key="DataTemplateFemale">
            <Grid Background="Pink">
                <TextBlock Text="{x:Bind Name}" />
            </Grid>
        </DataTemplate>

        <!--
            自定義數據模板選擇器(參見 code-behind 中的代碼)
        -->
        <local:MyDataTemplateSelector x:Key="MyDataTemplateSelector" 
                                      DataTemplate1="{StaticResource DataTemplateMale}"
                                      DataTemplate2="{StaticResource DataTemplateFemale}" />
    </Page.Resources>

    <Grid Background="Transparent">
        <StackPanel Margin="10 0 10 10" Orientation="Horizontal">

            <!--
                ItemsControl - 集合控件
                    ItemTemplateSelector - 每個數據項的數據模板選擇器(如果指定了 ItemTemplate 則此配置無效)
            -->
            <ListView Name="itemsControl" Margin="5" Width="400" Height="400" HorizontalAlignment="Left" VerticalAlignment="Top"
                      ItemsSource="{x:Bind Employees}"
                      ItemTemplateSelector="{StaticResource MyDataTemplateSelector}">

            </ListView>

        </StackPanel>
    </Grid>
</Page>

Controls/CollectionControl/ItemsControlDemo/ItemsControlDemo3.xaml.cs

/*
 * ItemsControl - 集合控件(繼承自 Control, 請參見 /Controls/BaseControl/ControlDemo/)
 * 
 * 
 * 本例用於演示 ItemsControl 如何通過 item 的不同而使用不同的數據模板
 */

using System.Collections.ObjectModel;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows10.Common;

namespace Windows10.Controls.CollectionControl.ItemsControlDemo
{
    public sealed partial class ItemsControlDemo3 : Page
    {
        public ObservableCollection<Employee> Employees { get; set; } = TestData.GetEmployees(100);

        public ItemsControlDemo3()
        {
            this.InitializeComponent();
        }
    }

    // 自定義 DataTemplateSelector(數據模板選擇器)
    // 可以實現在 runtime 時,根據 item 的不同選擇不同的數據模板
    public class MyDataTemplateSelector : DataTemplateSelector
    {
        // 數據模板 1(配置在 xaml 端)
        public DataTemplate DataTemplate1 { get; set; }

        // 數據模板 2(配置在 xaml 端)
        public DataTemplate DataTemplate2 { get; set; }

        // 根據 item 的數據的不同,指定的不同的模板
        protected override DataTemplate SelectTemplateCore(object item, DependencyObject container)
        {
            var employee = item as Employee;
            if (employee == null || employee.IsMale)
                return DataTemplate1; // 男員工用數據模板 1
            return DataTemplate2; // 女員工用數據模板 2

            // 如果想直接返回指定的資源也是可以的(但是不靈活),類似:return (DataTemplate)Application.Current.Resources["DataTemplateMale"];
        }
    }
}


2、ItemsControl 的數據分組
Controls/CollectionControl/ItemsControlDemo/ItemsControlDemo4.xaml

<Page
    x:Class="Windows10.Controls.CollectionControl.ItemsControlDemo.ItemsControlDemo4"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:Windows10.Controls.CollectionControl.ItemsControlDemo"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">

    <Page.Resources>

        <!--
            GroupStyle - 組樣式
                HidesIfEmpty - 空組是否隱藏
                HeaderContainerStyle - 組標題的容器樣式
                HeaderTemplate - 組標題的模板
                HeaderTemplateSelector - 組標題的模板選擇器
        
            注:
            ListView 的 Group 的 HeaderContainer 是 ListViewHeaderItem, GridView 的 Group 的 HeaderContainer 是 GridViewHeaderItem
            ListViewHeaderItem 和 GridViewHeaderItem 均繼承自 ListViewBaseHeaderItem, ListViewBaseHeaderItem 繼承自 ContentControl
        -->
        <GroupStyle x:Key="GroupStyle1" HeaderTemplate="{StaticResource DataTemplateGroupHeader}">
            <GroupStyle.HeaderContainerStyle>
                <Style TargetType="ListViewHeaderItem">
                    <Setter Property="Background" Value="Blue" />
                </Style>
            </GroupStyle.HeaderContainerStyle>
        </GroupStyle>
        <GroupStyle x:Key="GroupStyle2" HeaderTemplate="{StaticResource DataTemplateGroupHeader}">
            <GroupStyle.HeaderContainerStyle>
                <Style TargetType="ListViewHeaderItem">
                    <Setter Property="Background" Value="Orange" />
                </Style>
            </GroupStyle.HeaderContainerStyle>
        </GroupStyle>

        <DataTemplate x:Key="DataTemplateGroupHeader">
            <TextBlock Text="{Binding Title}" />
        </DataTemplate>

        <!--
            自定義 GroupStyle 選擇器(參見 code-behind 中的代碼)
        -->
        <local:MyGroupStyleSelector x:Key="MyGroupStyleSelector" 
                                      GroupStyle1="{StaticResource GroupStyle1}"
                                      GroupStyle2="{StaticResource GroupStyle2}" />
    </Page.Resources>

    <Grid Background="Transparent">
        <StackPanel Margin="10 0 10 10">

            <!--
                ItemsControl - 集合控件
                    ItemsPanel - 用於指定 items 的布局控件,任何 Panel 類型的布局控件均可,所有 items 將在 Panel 內顯示(Panel 是所有 items 的容器)
                        給 ItemsControl 用的,可虛擬化的布局控件有:ItemsStackPanel, ItemsWrapGrid, VirtualizingStackPanel, WrapGrid. 請參見:/Controls/CollectionControl/ItemsControlDemo/LayoutControl/
                    GroupStyle - 組樣式
                    GroupStyleSelector - 組樣式選擇器
            -->
            <ListView Name="listView" Margin="5" Width="400" Height="400" HorizontalAlignment="Left" ItemsSource="{x:Bind MyData.View}"
                      GroupStyleSelector="{StaticResource MyGroupStyleSelector}" SelectionChanged="listView_SelectionChanged">
                <!--
                <ListView.GroupStyle>
                    <GroupStyle>
                        <GroupStyle.HeaderTemplate>
                            <DataTemplate>
                                <TextBlock Text="{Binding Title}" />
                            </DataTemplate>
                        </GroupStyle.HeaderTemplate>
                    </GroupStyle>
                </ListView.GroupStyle>
                -->
                <ListView.ItemTemplate>
                    <DataTemplate>
                        <TextBlock Text="{Binding Title}" Foreground="Purple" />
                    </DataTemplate>
                </ListView.ItemTemplate>
                <ListView.ItemsPanel>
                    <ItemsPanelTemplate>
                        <ItemsStackPanel  />
                    </ItemsPanelTemplate>
                </ListView.ItemsPanel>
            </ListView>

            <TextBlock Name="lblMsg" Margin="5" />

        </StackPanel>
    </Grid>
</Page>

Controls/CollectionControl/ItemsControlDemo/ItemsControlDemo4.xaml.cs

/*
 * ItemsControl - 集合控件(繼承自 Control, 請參見 /Controls/BaseControl/ControlDemo/)
 *     IsGrouping - 當前 ItemsControl 顯示的是否是分組數據(只讀)
 *     DependencyObject GroupHeaderContainerFromItemContainer(DependencyObject itemContainer) - 獲取指定 ItemContainer 的 HeaderContainer
 *     
 *     
 * 本例用於演示如何通過 ItemsControl 顯示分組數據
 * 
 * 注:本例是用 ListView 來演示數據分組的,用 GridView 做數據分組的示例請參見 /Index.xaml
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Data;
using Windows10.Common;

namespace Windows10.Controls.CollectionControl.ItemsControlDemo
{
    public sealed partial class ItemsControlDemo4 : Page
    {
        public CollectionViewSource MyData
        {
            get
            {
                XElement root = XElement.Load("SiteMap.xml");
                var items = LoadData(root);

                // 構造數據源
                CollectionViewSource source = new CollectionViewSource();
                source.IsSourceGrouped = true;
                source.Source = items;
                source.ItemsPath = new PropertyPath("Items");

                return source;
            }
        }

        public ItemsControlDemo4()
        {
            this.InitializeComponent();

            this.Loaded += ItemsControlDemo4_Loaded;
        }

        private void ItemsControlDemo4_Loaded(object sender, RoutedEventArgs e)
        {
            lblMsg.Text = "IsGrouping: " + listView.IsGrouping.ToString();
        }

        private async void listView_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (e.AddedItems.Count > 0 && listView.ContainerFromItem(e.AddedItems[0]) != null)
            {
                // 獲取選中數據的 HeaderContainer
                ListViewHeaderItem headerContainer = listView.GroupHeaderContainerFromItemContainer(listView.ContainerFromItem(e.AddedItems[0])) as ListViewHeaderItem;

                NavigationModel headerNavigationModel = headerContainer.Content as NavigationModel;
                await new MessageDialog($"header: {headerNavigationModel.Title}").ShowAsync();
            }
        }

        // 解析 xml 數據
        private List<NavigationModel> LoadData(XElement root)
        {
            if (root == null)
                return null;

            var items = from n in root.Elements("node")
                        select new NavigationModel
                        {
                            Title = (string)n.Attribute("title"),
                            Url = (string)n.Attribute("url"),
                            Items = LoadData(n)
                        };

            return items.ToList();
        }
    }

    // 自定義 MyGroupStyleSelector(GroupStyle 選擇器)
    // 可以實現在 runtime 時,根據 group 的不同選擇不同的 GroupStyle
    public class MyGroupStyleSelector : GroupStyleSelector
    {
        static bool temp = false;

        // GroupStyle 1(配置在 xaml 端)
        public GroupStyle GroupStyle1 { get; set; }

        // GroupStyle 2(配置在 xaml 端)
        public GroupStyle GroupStyle2 { get; set; }

        protected override GroupStyle SelectGroupStyleCore(object group, uint level)
        {
            // 我這里測試,group 要么是 null 要么是 DependencyObject,level 總是 0

            // 利用這個變量,來演示如何讓不同的 group 使用不同的 GroupStyle
            temp ^= true;
            if (temp)
                return GroupStyle1;
            return GroupStyle2;

            // 如果想直接返回指定的資源也是可以的(但是不靈活),類似:return (GroupStyle)Application.Current.Resources["GroupStyle1"];
        }
    }
}



OK
[源碼下載]


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM