【问题标题】:CollectionViewSource doesn't sort after selecting new tab on TabControl在 TabControl 上选择新选项卡后 CollectionViewSource 不排序
【发布时间】:2016-07-30 22:39:22
【问题描述】:

我正在对显示在 TabControl 内的 UserControl 中的数据网格进行排序。

主窗口包含如下所示的 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>

当第一个选项卡被激活时,用户控件会正确地对数据网格进行排序。但是,当我单击其他选项卡或切换回原始选项卡时,数据网格不会排序。

<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)

为什么排序只在最初发生?

感谢您的帮助。

【问题讨论】:

    标签: wpf datagrid tabcontrol collectionviewsource


    【解决方案1】:

    这是因为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));
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-04-22
      • 2010-11-08
      • 1970-01-01
      • 1970-01-01
      • 2012-08-29
      • 1970-01-01
      • 2012-02-25
      • 2021-10-26
      相关资源
      最近更新 更多