I have a DataGrid, with columns XAML as such:
<DataGridTextColumn Header="Time" Binding="{Binding Date, StringFormat='yyyy-MM-dd HH:mm:ss'}" SortMemberPath="Date" SortDirection="Descending" Width="130" CanUserResize="True" />
<DataGridTextColumn Header="Level" Binding="{Binding Level}" Width="60" CanUserResize="True" />
<DataGridTextColumn Header="Source" Binding="{Binding Logger}" Width="150" CanUserResize="True" />
<DataGridTextColumn Header="Message" Binding="{Binding Message}" Width="*" CanUserResize="True" />
I bind this to an ObservableCollection<EalsLogEvent>
, where EalsLogEvent.Date
is typed DateTime
:
public ObservableCollection<EalsLogEvent> LogEvents
{
get
{
return _logEvents;
}
}
The grid viewmodel uses a timer to refresh itself, and everything seems fine with the grid, except when it first loads, on app startup. Then, the Time
column appears to be sorted descending, but is sorted ascending.
To get the sort right, I must click the column header twice; the first time changes the order to ascending, which now matches the content of the column. The second click on the column header changes its sort order back to descending, and this time it sorts the column contents properly, i.e. descending.
If I use LINQ to order the collection when _logEvents
gets refreshed, I lose whichever order the user had set for the column by clicking its header. If I have to have the view tell the model which order the LINQ sort should use, something smells bad.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…