Grouping and displaying a collection of events in a table with WPF
I'm after some WPF advice; I have a list of objects that define a time, event type and description like so:
public class AnEvent
{
public EventType EventType { get; set; }
public DateTime TimeStamp { get; set; }
public string Description { get; set; }
}
I want to display the collection of items like this:
-------------------------------------
| Time | Type1 | Type3 |
-------------------------------------
| 12:00 | Event1 | |
-------------------------------------
| 12:01 | Event2 | Event4 |
| | Event3 | |
-------------------------------------
| 12:05 | | Event5 |
-------------------------------------
What's the best way to display this data in WPF?
I've considered using a Grid, but I'm not sure how to
I've also considered preprocessing the list of events to generate a collection of events by time, and then a collection of events by type within that, and then using several ItemsControls to display the different levels.
What are my other options?
Thanks!
I would suggest that you write a simple VM as is
public class EventLogByTimeViewModel : ViewModelBase
{
public DateTime Time { get; set; }
public ObservableCollection<AnEvent> Type1Collection { get; set; }
public ObservableCollection<AnEvent> Type3Collection { get; set; }
}
And create a factory to which you would provide a list of AnEvent and which would output a list of VM
public interface IEventLogByTimeVMFactory
{
IList<EventLogByTimeViewModel> GenerateVM(IList<AnEvent>);
}
You could surely use the GroupBy
method from Linq extensions inside your factory implementation for an easier process.
Then in your high level view model (the one you bind to DataContext), expose and implement the collection of EventLogByTimeViewModel as is
public class MainViewModel : ViewModelBase
{
private IEventLogByTimeVMFactory _factory;
public MainViewModel()
{
EventLogs = new ObservableCollection<EventLogByTimeViewModel>();
_factory = new MyFactoryImplementation();
}
public ObservableCollection<EventLogByTimeViewModel> EventLogs { get; set; }
public void LoadData(IList<EventEventLogByTimeViewModel> eventLogs)
{
var vms = _factory.GenerateVM(eventLogs);
EventLogs.Clear();
foreache(vm in vms)
{
EventLogs.Add(vm);
}
}
}
The mecanism by which you would call the LoadData method is up to you.
Finally in your UI, I encourage you to use the DataGrid
control, bind the EventLogs
property to its ItemsSource
and finally implement DataTemplate
for both Type1 and Type3 columns that would display the EventType
collections inside a ItemsControl
.
下一篇: 使用WPF在表格中分组并显示一组事件