Currently visible columns in a wpf datagrid

I have a datagrid with more than 15 columns and a horizontal scroll bar is visible.How can I check whether a datagrid column is currently visible on screen or not in wpf.

1 answer

  • answered 2018-07-12 08:48 Andreas Zita

    This seem to work:

    public static bool IsVisibleInView(FrameworkElement element, FrameworkElement container)
    {
      if (!element.IsVisible) return false;
      var bounds = element.TransformToAncestor(container).TransformBounds(new Rect(0.0, 0.0,
        element.ActualWidth, element.ActualHeight));
      var rect = new Rect(0.0, 0.0, container.ActualWidth, container.ActualHeight);
      return rect.Contains(bounds.TopLeft) || rect.Contains(bounds.BottomRight);
    }
    
    public void Button_Click(object sender, RoutedEventArgs e)
    {
      var row = (DataGridRow)grid.ItemContainerGenerator.ContainerFromIndex(0);
      System.Windows.MessageBox.Show(IsVisibleInView(grid.Columns.Last().GetCellContent(row),
        grid) ? "Visible" : "Invisible");
    }
    

    At least it gives you a way of checking if a certain column is presented or not. You'll have to adapt it to your specific case.