在 DataGrid XAML 中,为 SelectedCellsChanged 设置事件处理程序:
SelectedCellsChanged="CustomGrid_SelectedCellsChanged"
现在,在您的代码隐藏中,添加事件处理程序的代码如下:
private void CustomGrid_SelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e)
{
foreach(DataGridCellInfo cellInfo in minorGrid.SelectedCells) // For each selected cell
{
DataGridCell cell = GetDataGridCell(cellInfo); // get the cell
string cellText = ((TextBlock)cell.Content).Text; // get the text of the cell
if (cellText.ToLower().Contains("off")) // If meets the conditino
cell.IsSelected = false; // unselect the cell
}
}
private DataGridCell GetCell(DataGridCellInfo cellInfo)
{
var cellContent = cellInfo.Column.GetCellContent(cellInfo.Item);
if (cellContent != null)
return (DataGridCell)cellContent.Parent;
return null;
}
当一个单元格被选中时,我们不会在 SelectedCells 列表中获得 DataGridCell 对象,而是获得 DataGridCellInfo 对象。为了获取 DataGridCell 对象,我提供了一个方法。一旦我们得到单元格对象,我们就可以对单元格执行逻辑。
这将从您的选择中取消选择所有带有“关闭”文本的单元格,这可能是节假日的情况:)。
同样,如果列标题包含“星期六”或“星期日”,您也可以取消选择整个列,具体取决于您对列的命名方式。只需更改以下几行
string cellText = ((TextBlock)cell.Content).Text; // get the text of the cell
if (cellText.ToLower().Contains("off")) // If meets the conditino
cell.IsSelected = false; // unselect the cell
到
string headerText = cell.Column.Header.ToString();
if (headerText.ToLower().Contains("saturday") || headerText.ToLower().Contains("sunday")) // If meets the conditino
cell.IsSelected = false; // unselect the cell
希望对你有帮助:)