在DataGrid完成使用异步ItemsSource加载后执行某些操作?

问题描述 投票:1回答:2

我有一个加载大量物品的DataGrid,所以我将ItemsSource设置为IsAsync=True

 <DataGrid Name="OrdersGrid" ItemsSource="{Binding Path=Orders, IsAsync=True}" />

除了在我的NewItemPlaceHolderPosition子类构造函数中更改UserControl之外,一切似乎都能正常工作。

((IEditableCollectionView)OrdersGrid.Items).NewItemPlaceholderPosition = NewItemPlaceholderPosition.AtBeginning;

我认为这会崩溃,因为你不能将它设置为空网格,这是我在异步ItemsSource绑定之前所拥有的。

那么在我尝试更改DataGrid之前,我应该把上面的行放在哪里以确保加载NewItemPlaceholderPosition?我需要像“DataGridFinishedLoading”这样的东西,但我不知道有什么可用。

wpf datagrid
2个回答
4
投票

Binding.NotifyOnTargetUpdated正是您要找的。

在绑定和钩子处理程序上将NotifyOnTargetUpdated设置为true,当Target(您的情况下为DataGrid)更新时需要调用它。

您可以查看args.Property已通知哪个绑定。

XAML

<DataGrid Name="OrdersGrid"
          ItemsSource="{Binding Path=Orders, IsAsync=True,
                                NotifyOnTargetUpdated=True}"
          TargetUpdated="DataGrid_TargetUpdated"/>

代码背后

private void DataGrid_TargetUpdated(object sender, DataTransferEventArgs e)
{
    if (e.Property == DataGrid.ItemsSourceProperty)
    {
        ((IEditableCollectionView)OrdersGrid.Items).NewItemPlaceholderPosition = 
                                   NewItemPlaceholderPosition.AtBeginning;
    }
}

2
投票

你可以检查StatusItemContainerGenerator,如果它完成生成,如果Items计数是0

public MainWindow()
{
    var datagrid = new DataGrid();
    datagrid.ItemContainerGenerator.StatusChanged += ItemContainerGeneratorOnStatusChanged;
}

private void ItemContainerGeneratorOnStatusChanged(object sender, EventArgs eventArgs)
{
    var dataGrid = sender as DataGrid;
    if (dataGrid == null) return;
    if (dataGrid.ItemContainerGenerator.Status == GeneratorStatus.ContainersGenerated)
    {
       ((IEditableCollectionView)OrdersGrid.Items).NewItemPlaceholderPosition = NewItemPlaceholderPosition.AtBeginning;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.