如何在wpf中更改datagrid的单个单元格颜色?

Viv*_*ikh 2 c# wpf xaml datagrid wpfdatagrid

舞台图表 我想在运行时更改此网格的特定单元格的背景颜色(显示已预订的座位).我从窗口加载的event.i上的数据表绑定此网格有一个像'A33'的席位记录.我的绑定代码就像这个.

MySqlConnection mycon = new MySqlConnection(str);
mycon.Open();
MySqlDataAdapter da = new MySqlDataAdapter("select * from Stage", mycon);
da.Fill(dt);
MyGrid.ItemsSource = dt.DefaultView;
Run Code Online (Sandbox Code Playgroud)

use*_*519 5

通过代码更改特定单元格的背景:

   DataGridRow firstRow = dataGrid1.ItemContainerGenerator.ContainerFromItem(dataGrid1.Items[0]) as DataGridRow;
   DataGridCell firstColumnInFirstRow = dataGrid1.Columns[0].GetCellContent(firstRow).Parent as DataGridCell;
   //set background
   firstColumnInFirstRow.Background = Brushes.Red;
Run Code Online (Sandbox Code Playgroud)


H.B*_*.B. 5

您的单元格数据应该具有属性IsBooked,然后DataGrid.CellStyle您可以使用数据触发器IsBooked来更改其背景.(还有一些其他的替代方案之外DataTriggers,但如果你只是有一个布尔条件我觉得他们是相当方便的.)