DataGrid列显示隐藏配置

1.列右键事件

 private void data1_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
        {
            ContextMenu context = new ContextMenu();
            MenuItem item = new MenuItem();
            item.Header = "请选择要隐藏显示的列";
            context.Items.Add(item);

            for (int i = 0; i < data1.Columns.Count;i++) {
                CheckBox box = new CheckBox();
                box.Content = data1.Columns[i].Header;
                if (data1.Columns[i].Visibility == Visibility.Collapsed) {
                    box.IsChecked = true;
                }
                box.Click += new RoutedEventHandler(box_click);
                context.Items.Add(box);
            }
            context.IsOpen = true;
            ContextMenuService.SetContextMenu(data1,context);
        }

 

2.对应列复选框选中事件

 1 private void box_click(object sender, RoutedEventArgs e)
 2         {
 3             CheckBox box = (CheckBox)sender;
 4             for (int i = 0; i < data1.Columns.Count;i++) {
 5                 if (box.Content == data1.Columns[i].Header) {
 6                     if (data1.Columns[i].Visibility == Visibility.Collapsed)
 7                         data1.Columns[i].Visibility = Visibility.Visible;
 8                     else
 9                         data1.Columns[i].Visibility = Visibility.Collapsed;
10                 }
11             }
12         }

 

posted on 2020-10-23 18:03  写abcd的猴子  阅读(336)  评论(0编辑  收藏  举报