2012-07-23 91 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,我想其他人有更好的解決方案升值

相關問題