1

ListBoxCollectionView以编程方式使用源进行分组:

喜欢

Task 1 (certain date)
Task 2 (certain date)
Task 3 (certain date)
Task 4 (certain date)

Certain date1  
  Task 1
  Task 3  
Certain date2
  Task 2
  Task 4
4

1 回答 1

9

这是给你的一个样本。

XAML:

<Window x:Class="TestWPFApp.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="695" Width="996" Loaded="Window_Loaded">
    <Grid>
        <ListBox Height="100" HorizontalAlignment="Left" Margin="10,10,0,0" Name="lbxTasks" VerticalAlignment="Top" Width="120">
            <ListBox.GroupStyle>
                <GroupStyle />
            </ListBox.GroupStyle>
           <ListBox.ItemTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding Title}"/>
            </DataTemplate>
           </ListBox.ItemTemplate>
        </ListBox>
    </Grid>
</Window>

代码背后:

 public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private List<Task> MyTasks()
        {
            List<Task> tasks = new List<Task>();
            DateTime date = DateTime.Now;
            tasks.Add(new Task { CreatedDate = date, Title = "Task 1" });
            tasks.Add(new Task { CreatedDate = date, Title = "Task 2" });
            tasks.Add(new Task { CreatedDate = date.AddDays(-1), Title = "Task 3" });
            tasks.Add(new Task { CreatedDate = date.AddDays(-1), Title = "Task 4" });
            return tasks;
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            ICollectionView _tasksView = CollectionViewSource.GetDefaultView(MyTasks());
            _tasksView.GroupDescriptions.Add(new PropertyGroupDescription("CreatedDate"));
            lbxTasks.ItemsSource = _tasksView ;
        }
    }

    public class Task
    {
        public DateTime CreatedDate { get; set; }
        public string Title { get; set; }
    }

输出:

在此处输入图像描述

于 2012-05-25T06:10:49.730 回答