Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if Item in a DataGrid is already in view

Tags:

c#

wpf

datagrid

I have a DataGrid where the ItemsSource is bound to an ObservableCollection<LogEntry>. On a click on a Button the user can scroll to a specific LogEntry. Therefor I use the following code:

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

This just works fine. But what I don't like is: If the LogEntry already is in view then the DataGrid flickers shortly.

My question now is:

Is there a possibility to check on the DataGrid if the given LogEntry already is in view?

like image 281
Tomtom Avatar asked Oct 31 '22 06:10

Tomtom


1 Answers

You can get index for first visible item and last visible item

then you can check if your item's index was within first and last or not.

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

Get Scrollbar method

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;
    } 
like image 88
Muds Avatar answered Nov 13 '22 03:11

Muds