问题
I need to know is it possible to disable a specific cell edit in a DataGrid, without disabling edit for the entire column in Silverlight 4. I can get the specific cell object as a FrameworkElement but it does not contain property IsReadOnly or IsEnabled. You will probably ask: Why do I need that? Well my application requires disabling particular cells in row depending on the other cell content. Each row is being checked this way separately. If you have an idea how I can achieve such a unusual behaviour please write ;)
回答1:
If you have the row,column index of the cell/cells that you wish to have disabled:
int r = 2, c = 4;
Then you can listen to the events CellEnter and CellLeave and do the following:
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;
}
}
}
You're still setting the entire column to Readonly, but since you are resetting it back after you leave the cell it has the effect of appearing to only work for the cell.
回答2:
You can use IsReadOnly Attribute for particular cell like this
<DataGridTextColumn Header="ID"
Binding="{Binding ID}"
IsReadOnly="True"/>
I this this is best idea for disabling a specific cell. Thanks
回答3:
Thanks NominSim, This helps me me to solve my proplem too, but as neurotix didnt find CellEnter and CellLeave methods on my DataGrid in SilverLight 4.
As NominSim said, you need to know the index of row and the column.
How i solve it:
Disable editing
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;
}
}
Enable editing
After some milliseconds the timer make the column enabled:
void timer_Tick(object sender, EventArgs e)
{
dataGrid1.Columns[yourColumnIndex].IsReadOnly = false;
timMakeEditable.Stop();
}
I think is a better idea use cellEditEnded, but it didnt work for me.
来源:https://stackoverflow.com/questions/9129336/disabling-specific-cell-edit-in-datagrid