Ashwin Nagarajan
Ashwin Nagarajan

Reputation: 219

LISTBOX grouping using collectionView Source

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

Upvotes: 1

Views: 3734

Answers (1)

Bilal Hashmi
Bilal Hashmi

Reputation: 1485

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

Upvotes: 9

Related Questions