加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 检查DataGrid中的Item是否已在视图中

发布时间:2020-12-15 22:12:58 所属栏目:百科 来源:网络整理
导读:我有一个DataGrid,其中ItemsSource绑定到ObservableCollection LogEntry.单击按钮,用户可以滚动到特定的LogEntry.因此我使用以下代码: private void BringSelectedItemIntoView(LogEntry logEntry){ if (logEntry != null) { ContentDataGrid.ScrollIntoVie
我有一个DataGrid,其中ItemsSource绑定到ObservableCollection< LogEntry>.单击按钮,用户可以滚动到特定的LogEntry.因此我使用以下代码:

private void BringSelectedItemIntoView(LogEntry logEntry)
{
    if (logEntry != null)
    {
        ContentDataGrid.ScrollIntoView(logEntry);
    }
}

这只是工作正常.但我不喜欢的是:如果LogEntry已经在视图中,那么DataGrid很快就会闪烁.

我现在的问题是:

如果给定的LogEntry已经在视图中,是否有可能检查DataGrid?

解决方法

您可以获取第一个可见项目和最后一个可见项目的索引

然后你可以检查你的项目的索引是否在第一个和最后一个之内.

var verticalScrollBar = GetScrollbar(DataGrid1,Orientation.Vertical);
var count = DataGrid1.Items.Count;
var firstRow = verticalScrollBar.Value;
var lastRow = firstRow + count - verticalScrollBar.Maximum;

// check if item index is between first and last should work

获取Scrollbar方法

private static ScrollBar GetScrollbar(DependencyObject dep,Orientation orientation)
    {
        for (int i = 0; i < VisualTreeHelper.GetChildrenCount(dep); i++)
        {
            var child = VisualTreeHelper.GetChild(dep,i);
            var bar = child as ScrollBar;
            if (bar != null && bar.Orientation == orientation)
                return bar;
            else
            {
                ScrollBar scrollBar = GetScrollbar(child,orientation);
                if (scrollBar != null)
                    return scrollBar;
            }
        }
        return null;
    }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读