Reputation: 1246
I'm building a WPF app, and I would like my DataGrid to be able to hide columns very similar to the way Excel does. I have a right click menu that pops up with 'hide column' as an option. Here is how that works:
if (dgfinal_Copy.CurrentCell.Column == null)
{
}
else
{
int columnIndex = dgfinal_Copy.CurrentCell.Column.DisplayIndex;
dgfinal_Copy.Columns[columnIndex].Visibility = Visibility.Collapsed;
}
I had to add the if statement because if someone clicked the header before clicking in the grid then the current cell would be null. Also if I click a cell in column [2] but then click the header of [0] and then click 'hide column' from my menu, as you could have guessed, it's [2] that gets hidden and not [0].
I would like to alter this to use the column index of the header (if that is where the cursor is) and if not then the column index of the current cell.
I'm adding the full method that I'm using to see if i'm overlooking something easy:
private void WorkItemsGrid_Hide(object sender, RoutedEventArgs e)
{
if (dgfinal_Copy.CurrentCell.Column == null)
{
}
else
{
int colIn = dgfinal_Copy.SelectedCells[0].Column.DisplayIndex;
System.Windows.MessageBox.Show(colIn.ToString());
int columnIndex = dgfinal_Copy.CurrentCell.Column.DisplayIndex;
dgfinal_Copy.Columns[columnIndex].Visibility = Visibility.Collapsed;
}
}
<MenuItem Header="Unhide All Columns" Click="WorkItemsGrid_UnHide" />
Upvotes: 0
Views: 1074
Reputation: 495
The following is working with my base code. As it stands, it returns the column index of the column header clicked. You should be able to adapt it to your exact needs.
XAML:
<DataGrid Name="dtgrdNotes" MouseRightButtonUp="DataGrid_Click">
<DataGrid.ContextMenu>
<ContextMenu MenuItem.Click="menuItem_Click">
<MenuItem Name="hide" Header="Hide"/>
</ContextMenu>
</DataGrid.ContextMenu>
</DataGrid>
Code Behind:
DependencyObject mainDep = new DependencyObject();
private void DataGrid_Click(object sender, RoutedEventArgs e)
{
DependencyObject dep = (DependencyObject)e.OriginalSource;
while ((dep != null) && !(dep is DataGridCell) && !(dep is DataGridColumnHeader))
{
dep = VisualTreeHelper.GetParent(dep);
}
mainDep = dep;
}
private void menuItem_Click(object sender, RoutedEventArgs e)
{
DependencyObject dep = mainDep;
int index = -1;
if (dep is DataGridColumnHeader)
{
DataGridColumnHeader header = dep as DataGridColumnHeader;
index = header.DisplayIndex;
dtgrdNotes.Columns[index].Visibility = Visibility.Collapsed;
}
if (dep is DataGridCell)
{
DataGridCell cell = dep as DataGridCell;
index = cell.Column.DisplayIndex;
dtgrdNotes.Columns[index].Visibility = Visibility.Collapsed;
}
label.Content = index;
}
This should work for both a cell and column header click.
Upvotes: 1