ListBox
以编程方式使用CollectionView
源进行分组:
喜欢
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
答案 0 :(得分: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; }
}
<强>输出:强>