关闭并打开列可见性

时间:2010-07-04 15:21:58

标签: wpf datagrid

我有一个包含许多列的DataGrid,我想为用户提供一个下拉列表,允许他们选择可以看到的列。我在桌面应用程序中使用.Net 4 WPF DataGrid。

有没有人知道一种简单的方法来完成我想要做的事情。

1 个答案:

答案 0 :(得分:1)

我这样做如下。

我从网格中派生出一个名为HideShowColumnCommand的ICommand,它将DataGridColumn(我要隐藏或显示的那个)作为参数,如果它可见则隐藏列,如果不可见则显示它。

然后我使用一个棘手的上下文菜单,我附加到列标题,其中有一个勾号,显示列可见/隐藏状态..

上下文菜单如此

<ContextMenu
   ItemsSource="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Column.DataGridOwner.Columns}">
   <ContextMenu.Resources>
      <local:DataGridHeaderVisibilityToBooleanConverter
         x:Key="visibilityConverter" />
      <BooleanToVisibilityConverter
         x:Key="VisibilityOfBool" />

      <DataTemplate
         DataType="{x:Type DataGridColumn}">
         <ContentPresenter
            Content="{Binding Path=Header}"
            RecognizesAccessKey="True" />
      </DataTemplate>

   </ContextMenu.Resources>
   <ContextMenu.ItemContainerStyle>
      <Style
         TargetType="MenuItem">
         <!--Warning dont change the order of the following two setters
                   otherwise the command parameter gets set after the command fires,
                   not much use eh?-->
         <Setter
            Property="CommandParameter"
            Value="{Binding Path=.}" />
         <Setter
            Property="Command"
            Value="{Binding Path=DataGridOwner.HideShowColumnCommand}" />
         <Setter
            Property="IsChecked"
            Value="{Binding Path=Visibility, Converter={StaticResource visibilityConverter}}" />
      </Style>
   </ContextMenu.ItemContainerStyle>
</ContextMenu>  

像这样的转换器

public class DataGridHeaderVisibilityToBooleanConverter :IValueConverter{
  #region IValueConverter Members

  public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
     try {

        Visibility visibility = (Visibility)value;
        if (visibility == Visibility.Visible) {
           return true;
        }
        else {
           return false;
        }
     }
     catch { }
     return null;
  }

  public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
     throw new NotImplementedException();
  }

  #endregion
}