1

ListBox grouping using CollectionView source programmatically:

like

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

to

Certain date1  
  Task 1
  Task 3  
Certain date2
  Task 2
  Task 4
Termininja
  • 6,620
  • 12
  • 48
  • 49
Ashwin Nagarajan
  • 219
  • 4
  • 13
  • what does the data actually look like? What do you want the output to look like? What have you tried? – Matt Lacey May 25 '12 at 08:30
  • Matt Sorry for the Late reply, its just that i need to group list box items based on date, with date as group heading, like People Hub Appin windows phone 7, i have seen longlist selector , buts thats too big for my Design ,my list box items may/may not have more than 7 to 8 items ( like daily tasks ). – Ashwin Nagarajan May 29 '12 at 04:20
  • that answers none of my questions. See http://tinyurl.com/so-hints for hints on how you can ask a question we can answer – Matt Lacey May 29 '12 at 08:24

1 Answers1

9

Here is a sample for you.

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>

Code Behind:

 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; }
    }

Output:

enter image description here

Bilal Hashmi
  • 1,465
  • 13
  • 12