在TabControl

时间:2016-07-30 22:39:23

标签: wpf datagrid tabcontrol collectionviewsource

我正在对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)

为什么排序最初只发生?

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

这是因为DataGrid的工作方式。在设置DataGrid之前,SortDescriptions会清除ItemsSource

如果我们可以在SortDescriptions DataGrid完成ItemsSource之后应用我们的SortDescriptions,我们的TargetUpdated将会有效。

NotifyOnTargetUpdated=True事件来拯救,但要使用它,我们必须在Binding中设置<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));
}

代码:

LinearLayout rootView = (LinearLayout) findViewById(R.id.rootView);

        for (int i = 0; i < 10; i++) {
            TextView numberView = new TextView(this);
            numberView.setText(numbers.get(i));
            // adds a Text View to the Linear Layout (adding child to the parent) 
            rootView.addView(numberView);
        }