2016-07-30 65 views
0

我正在对TabControl内显示的UserControl内的数据网格进行排序。在TabControl上选择新选项卡后,CollectionViewSource不能排序

主窗口包含TabControl,如下所示。

<Grid> 
    <TabControl x:Name="EquipTabs" ItemsSource="{Binding Equipment}" > 
     <TabControl.ItemTemplate> 
      <DataTemplate> 
       <TextBlock Text="{Binding Name}" /> 
      </DataTemplate> 
     </TabControl.ItemTemplate> 
     <TabControl.ContentTemplate> 
      <DataTemplate> 
       <ctrls:MachData DataContext="{Binding Path=MachineViewModel}" /> 
      </DataTemplate> 
     </TabControl.ContentTemplate> 
    </TabControl> 
</Grid> 

当第一个选项卡被激活时,用户控件正确地对datagrid进行排序。但是,当我点击不同的选项卡或切换回原来的,datagrid不排序。

<UserControl.Resources> 
    <CollectionViewSource x:Key="StatesSource" Source="{Binding States}" > 
     <CollectionViewSource.SortDescriptions> 
      <scm:SortDescription PropertyName="StartTime" Direction="Descending" /> 
     </CollectionViewSource.SortDescriptions> 
    </CollectionViewSource> 
</UserControl.Resources> 

<Grid> 
    <DataGrid x:Name="dgStates" Grid.Row="2" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" 
       ItemsSource="{Binding Source={StaticResource StatesSource}}"> 
    </DataGrid> 
</Grid> 

的结合显示下列跟踪:

Deactivate 
    Replace item at level 0 with {NullDataItem} 
    Activate with root item MachDataViewModel (hash=25379957) 
    At level 0 using cached accessor for MachDataViewModel.States: RuntimePropertyInfo(States) 

为什么那种最初只发生?

感谢您的任何帮助。

回答

0

发生这种情况的原因是DataGrid的工作方式。 DataGrid在设置ItemsSource之前清除SortDescriptions

如果我们可以在DataGrid完成ItemsSource后申请我们的SortDescriptions,我们的SortDescriptions将工作。

TargetUpdated事件来救援,但要使用它,我们必须在我们的Binding设置NotifyOnTargetUpdated=True

<DataGrid 
    TargetUpdated="dgStates_TargetUpdated" 
    ItemsSource="{Binding Source={StaticResource StatesSource}, NotifyOnTargetUpdated=True}" /> 

代码:

private void dgStates_TargetUpdated(object sender, DataTransferEventArgs e) 
{ 
    CollectionViewSource sc = this.Resources["StatesSource"] as CollectionViewSource; 
    sc.SortDescriptions.Add(new System.ComponentModel.SortDescription("Name", System.ComponentModel.ListSortDirection.Ascending)); 
} 
相关问题