- 首先,可以通过使用DataGrid.CellStyle属性来定制单元格外观。为了突出显示单元格,可以将Background属性设置为需要的颜色或渐变。
<DataGrid.CellStyle>
<Style TargetType="{x:Type DataGridCell}">
<Setter Property="Background" Value="Yellow"/>
</Style>
</DataGrid.CellStyle>
- 然后,可以使用DataGrid.SelectedCellsChanged事件来捕获选择单元格的更改。在事件处理程序中,可以检查所选单元格的值,并对其进行更改。
private void dataGrid_SelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e)
{
foreach (DataGridCellInfo cellInfo in e.AddedCells)
{
// 获取单元格中的值
DataRowView drv = (DataRowView)cellInfo.Item;
string cellValue = drv[cellInfo.Column.Header.ToString()].ToString();
// 在此处修改单元格值
}
}
- 如果需要从DataSet更新DataGrid,可以使用DataSet的DataAdapter和DataView类。首先,创建一个DataAdapter并将其用于从数据源填充DataSet。然后,将该DataSet转换为DataView,并将DataView用作DataGrid的数据源。
// 创建DataAdapter并使用它填充DataSet
string connectionString = "connection string";
string sql = "select * from MyTable";
SqlConnection conn = new SqlConnection(connectionString);
SqlDataAdapter da = new SqlDataAdapter(sql, conn);
DataSet ds = new DataSet();
da.Fill(ds);
// 将DataSet转换为DataView并用作DataGrid数据源
DataView dv = ds.Tables[0].DefaultView;
dataGrid.ItemsSource = dv;