2012-02-03 65 views
2

我需要知道是否可以禁用DataGrid中的特定單元格編輯,而不是禁用了Silverlight 4中整個列的編輯。我可以將特定單元格對象作爲FrameworkElement獲取,但它不包含屬性IsReadOnly或IsEnabled。 您可能會問:爲什麼我需要這個?那麼我的應用程序需要根據其他單元格內容禁用行中的特定單元格。每行都是以這種方式單獨檢查。 如果你有一個想法,我怎麼能達到這樣一個不尋常的行爲,請寫;)禁用DataGrid中的特定單元格編輯

回答

1

如果你有行,單元格的列索引/您希望禁用了細胞:

int r = 2, c = 4; 

然後你可以聽的事件CellEnter和CellLeave並執行以下操作:

private void dataGridView1_CellEnter(object sender, DataGridViewCellEventArgs e) 
    { 
     if (e.RowIndex == r) 
     { 
      if (e.ColumnIndex == c) 
      { 
       dataGridView1.Columns[e.ColumnIndex].ReadOnly = true; 
      } 
     } 
    } 

    private void dataGridView1_CellLeave(object sender, DataGridViewCellEventArgs e) 
    { 
     if (e.RowIndex == r) 
     { 
      if (e.ColumnIndex == c) 
      { 
       dataGridView1.Columns[e.ColumnIndex].ReadOnly = false; 
      } 
     } 
    } 

你還是設置爲只讀整列,但因爲你是重置回你離開它出現的效應細胞後,只爲細胞工作。

+1

我用了一點不同的方法。我迷上了DataGrid的CurrentCellChanged事件和CellEditEnded事件。但這個想法真的很有幫助。謝謝! – neurotix 2012-02-13 13:48:06

+0

小心與我們分享您是如何實施這個的?謝謝。 – tobewan 2012-08-22 21:17:56

+0

你不知道什麼**布爾邏輯**是,是嗎? – Arnthor 2012-12-06 12:19:26

0

感謝NominSim,這可以幫助我我解決proplem太多,但作爲neurotix 沒有找到CellEnter和CellLeave方法在我的DataGrid中在Silverlight 4

正如NominSim說,你需要知道的行索引和列。

我如何解決這個問題:

禁用編輯

System.Windows.Threading.DispatcherTimer timMakeEditable = new System.Windows.Threading.DispatcherTimer(); 

    private void dataGrid1_PreparingCellForEdit(object sender, DataGridPreparingCellForEditEventArgs e) 
{ 
    timMakeEditable.Interval = new TimeSpan(0, 0, 0, 0, 100); // 100 Milliseconds 
    timMakeEditable.Tick += new EventHandler(timer_Tick); 
    timMakeEditable.Start(); 

    if (e.RowIndex == r && e.ColumnIndex == c) 
    { 
      dataGrid1.Columns[yourColumnIndex].IsReadOnly = true;  
    } 
} 

啓用編輯

幾毫秒後,定時器使能列:

void timer_Tick(object sender, EventArgs e) 
    { 
     dataGrid1.Columns[yourColumnIndex].IsReadOnly = false; 
     timMakeEditable.Stop(); 

    } 

我認爲使用cellEditEnded是一個更好的主意,但它並不適合我。

0

您可以使用特定的細胞IsReadOnly屬性這樣

<DataGridTextColumn Header="ID" 
             Binding="{Binding ID}" 
             IsReadOnly="True"/> 

我這個這是禁用特定細胞最好的主意。 謝謝