gpt4 book ai didi

c# - Wpf 数据网格 : how to detect the set of visible cells?

转载 作者:太空宇宙 更新时间:2023-11-03 14:40:24 25 4
gpt4 key购买 nike

我有一个 Wpf DataGrid,用户可以通过单击任何标题进行排序,然后滚动。有些单元格需要显示图像,但我想避免在填充 DataGrid 时加载所有图像。相反,我希望仅在图像进入视野时才加载图像。当单元格进入 View 时如何通知我,以及如何获取其绑定(bind)项?

最佳答案

我最终得到了这个解决方案:监听 DataGrid 的 ScrollViewer.ScrollChanged 事件:

<DataGrid ScrollViewer.ScrollChanged="DataGrid_ScrollChanged">

然后,使用 scrollviewer 属性检测可见行;最后使用 DataGrid 的 ItemContainerGenerator 来获取与感兴趣的每一行关联的项目。

    private static T GetChildOfType<T>(DependencyObject depObj)
where T : DependencyObject
{
if (depObj == null) return null;

for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
{
var child = VisualTreeHelper.GetChild(depObj, i);

var result = (child as T) ?? GetChildOfType<T>(child);
if (result != null) return result;
}
return null;
}

private void DataGrid_ScrollChanged(object sender, ScrollChangedEventArgs e)
{
var scroll = GetChildOfType<ScrollViewer>((DependencyObject)sender);
int firstRow = (int)scroll.VerticalOffset;
int lastRow = (int)scroll.VerticalOffset + (int)scroll.ViewportHeight + 1;
DataGrid datagrid = sender as DataGrid;
for (int i = firstRow; i < lastRow; i++)
{
var row = datagrid.ItemContainerGenerator.ContainerFromIndex(i) as DataGridRow;
if (row != null)
{
var item = row.DataContext;
ItemViewModel viewModel = item as ItemViewModel;
if (viewModel != null)
{
viewModel.LoadImages().ContinueWith(t => { });
}
}
}
}

关于c# - Wpf 数据网格 : how to detect the set of visible cells?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57159243/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com