2012-07-23 86 views
0

我正在使用DataGrids在WPF项目上工作,我试图让用户选择尽可能多的行,或者只有一个单元格,即禁用选择单元格范围。但我还没有做到这一点。只在DataGrid中选择多行或单个单元格

这可能吗?

我曾尝试下面的代码:

public MyDataGrid : DataGrid 
{ 
    public ExtendedDataGrid() 
    { 
     SelectionMode = DataGridSelectionMode.Extended; 
     SelectionUnit = DataGridSelectionUnit.CellOrRowHeader; 
     this.SelectedCellsChanged += new SelectedCellsChangedEventHandler(MyDataGrid_SelectedCellsChanged); 
    } 

    void MyDataGrid_SelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e) 
    { 
     if (this.SelectedCells.Count > 1) 
     {     
      DataGridCellInfo currentCell = this.CurrentCell; 
      this.SelectedCells.Clear(); 
      this.CurrentCell = currentCell; 
     } 
    } 

但这代码不允许我选择一整行。

那么,有没有办法根据需要选择尽可能多的行,但阻止用户选择单元格范围?

在此先感谢。

回答

1

我想我已经解决了我的问题:

private void MyDataGrid_SelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e) 
    { 
     int columnsCount = this.Columns.Count; 
     int selectedCells = SelectedCells.Count; 
     int selectedItems = SelectedItems.Count; 

     if (selectedCells > 1) 
     { 
      if (selectedItems == 0 || selectedCells % selectedItems != 0) 
      { 
       DataGridCellInfo cellInfo = SelectedCells[0]; 
       SelectedCells.Clear(); 
       SelectedCells.Add(cellInfo); 
       CurrentCell = SelectedCells[0]; 
      } 
     } 
    } 

我知道这是不是一个完美的解决方案,但到目前为止,这个工程作为espected,我想其他人有更好的解决方案升值

相关问题