WPF DataGrid点击有效区域Check

时间:2021-10-06 01:04:07

1、DataGrid注册左键事件,点击有效区域Check

//在窗体Load中增加 this.dataGrid.AddHandler(DataGrid.MouseLeftButtonDownEvent, new MouseButtonEventHandler(this.DataGrid_MouseLeftSingleButtonDown), true); //添加右键事件 private void DataGrid_MouseLeftSingleButtonDown(){ if(Utility.ignoreDataGridMouseLeftSingleButtonDown(sender,e) == false){ SelectedChange(); } } //DataGrid 点击检查判断 //用户是否点击在了DataGrid有效区域,而不是表格内空白,滚动条,,列名等无效区域 //返回值true:忽略该鼠标点击事件 public static bool ignoreDataGridMouseLeftSingleButtonDown(object sender,MouseButtonEventArgs e){ DataGrid grid = sender as DataGrid; if(grid == null || (grid.DataContext == null && grid.ItemsSource == null)){ return true; } bool isDataContextNull = false; if(grid.DataContext == null && grid.ItemsSource != null){ isDataContextNull = true; grid.DataContext = grid.ItemsSource; } bool ignored = false; Point p = e.GetPosition(grid); if(grid.VerticalScrollBarVisibility == ScrollBarVisibility.Visible){ if(p.X > grid.ActualWidth - SystemParameters.VerticalScrollBarWidth){ ignored = true; } } if(ignored == false && grid.HorizontalScrollBarVisibility == ScrollBarVisibility.Visible){ if(p.Y > grid.ActualHeight - SystemParameters.HorizontalScrollBarWidth || p.Y < grid.ColumnHeaderHeight){ ignored = true; } } //点击在表头 if(ignored == false){ DataGridColumnHeadersPresenter headerPresenter = FindVisualChild<DataGridColumnHeadersPresenter>(grid); if(p.Y < headerPresenter.ActualHeight){ ignored = true; } } //数据行是否显示满了 是否有空白区域 if(ignored == false){ //其绑定的上下文不是一个List类型 if(grid.DataContext.GetType().GetProperty("Count") ==null){ if(isDataContextNull){ grid.DataContext = null; } return ture; } //如果有数据 计算是否点在空白区域 int count; if(int.TryParse(grid.DataContext.GetType().GetProperty("Count").GetValue(grid.DataContext).ToString(), out count)){ double totalHeight = 0; for(int i=0;i<count ; i++){ DataGridRow row = (DataGridRow)grid.ItemContainerGenerator.ContainerFromIndex(i); if(row != null){ totalHeight += row.ActualHeight; } } if(totalHeight +grid.ColumnHeaderHeight < p.Y){ ignored = true; } } } if(isDataContextNull){ grid.DataContext = null; } return ignored; } public static T FindVisualChild<T>(DependencyObject current) where T :DependencyObject{ if(current == null) return null; int childCount = VisualTreeHelper.GetChildrenCount(current); for(int i=0; i< childCount; i++){ DependencyObject child = VisualTreeHelper.GetChild(current, i); if(child is T)return (T)child; T result = FindVisualChild<T>(child); if(result != null) return result; } return null; }

WPF DataGrid点击有效区域Check

标签:

原文地址:https://www.cnblogs.com/DingGuo/p/14515661.html