Is it possible to hide columns in WPF DataGrid whe

2019-08-04 20:25发布

I'm trying with example from here

http://msdn.microsoft.com/en-us/library/ff407126

I would like to add a control that user can define which columns are visible. Can this be done easily?

I found http://www.thomaslevesque.com/2011/03/21/wpf-how-to-bind-to-data-when-the-datacontext-is-not-inherited/ but it's different since it's not using CollectionView and CollectionViewSource.

Thanks & BR -Matti

1条回答
Rolldiameter
2楼-- · 2019-08-04 20:52

It can be done many ways. One way is to edit the Style for DataGrid's column headers. An example of a style for column headers can be found in :

Change WPF DataGrid Column Header Style, Menu Visibility in Code Behind?

Instead of having menu in ControlTemplate like in article above there can be a button like here for the column header:

<Button Grid.Column="2" Name="MultiButton" MouseRightButtonDown="MultiButton_MouseRightButtonDown" Click="MultiButton_Click" Visibility="Hidden">X</Button>

Button opens popupmenu with 2nd mouse button and click is supposed to remove the column. The button is hidden by default so there has to be trigger to make button visible when mouse moves to column header:

<Trigger Property="IsMouseOver" Value="True" >
    <Setter Property="Visibility" TargetName="DeleteColumn" Value="Visible" />                            
</Trigger>

Because all the columns have the button the click event have to sort out which column to hide:

private void MultiButton_Click(object sender, RoutedEventArgs e)
{
   object dataContext = ((FrameworkElement)sender).DataContext;
   foreach (DataGridColumn col in dataGrid1.Columns)
   {
       if (col.Header.ToString() == dataContext.ToString())
       {
           col.Visibility = Visibility.Hidden;
       }
   }
}

This might not be the best way to do it, but it works.

查看更多
登录 后发表回答