场景:一个数据网格,用于显示来自自定义来源的自定义事件。 网格必须按来源对行进行分组,按日期时间降序对事件进行排序(更新始终在顶部)。不允许手动排序,启用虚拟化,MVVM模式。 这是我的问题:组标题本身必须遵循日期时间顺序,也就是说,包含最新事件的组必须扩展到顶部。
ViewModel:
public class Event
{
public Int32 Source_Id { get; set; }
public String Source_Name { get; set; }
public DateTime Event_DateTime { get; set; }
}
CollectionView按Source_Id分组,并按Event_DateTime排序:
<CollectionViewSource x:Key='alarms_src' Source="{Binding Alarms}">
<CollectionViewSource.GroupDescriptions>
<PropertyGroupDescription PropertyName="Source_Id" />
</CollectionViewSource.GroupDescriptions>
<CollectionViewSource.SortDescriptions>
<scm:SortDescription PropertyName="Event_DateTime" Direction="Descending" />
</CollectionViewSource.SortDescriptions>
</CollectionViewSource>
GroupStyle是一个简单的扩展器,其标题中带有源名称和最新事件日期时间:
<DataGrid.GroupStyle>
<GroupStyle>
<GroupStyle.ContainerStyle>
<Style TargetType="{x:Type GroupItem}">
<Setter Property="Margin" Value="4"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type GroupItem}">
<Expander IsExpanded="True" Background="LightGray">
<Expander.Header>
<StackPanel Orientation="Horizontal" Background="Transparent">
<TextBlock Margin="8" Text="{Binding Items[0].Source_Name}"/>
<TextBlock Margin="8" Text="{Binding Items[0].Event_DateTime}"/>
</StackPanel>
</Expander.Header>
<Expander.Content>
<ItemsPresenter/>
</Expander.Content>
</Expander>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</GroupStyle.ContainerStyle>
</GroupStyle>
</DataGrid.GroupStyle>
输出: simplified grid
图像中的红色箭头指向我生成的第4行,带有最新时间戳。 网格可以正确地对每个组进行分组和排序,但是我希望Device_1组可以在网格的顶部扩展:如何获得它?
答案 0 :(得分:0)
CollectionViewSource.GetDefaultView(testdg.ItemsSource).Refresh();
testdg是我的DataGrid控件名称。
我认为是刷新datagrid的itemsource,其余的排序将得到照顾。签出方法。
private void addEvent(Int32 source)
{
Event a = new Event();
a.Source_Id = source;
a.Source_Name = "Device_" + source.ToString();
a.Event_DateTime = DateTime.Now;
this.Alarms.Add(a);
CollectionViewSource.GetDefaultView(testdg.ItemsSource).Refresh();
}
对不起,以前误解了您的问题。